React - Uncaught TypeError: Cannot read properties of undefined (reading 'setState')

React - Uncaught TypeError: Cannot read properties of undefined (reading 'setState')

我无法 setState 在回调函数中获取 S3 上传的进度百分比。

我想做的是从电脑上选择一个文件,将其上传到 S3 并在我的 dom 中呈现它并带有进度条。

class Dashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = { uri: "", uploadProgress : 0 };
    }

    async onChange(e) {
        const file = e.target.files[0];

        //upload to S3, works great
        try {
            await Storage.put(file.name, file, {
                progressCallback(progress) {
                    const prog = parseInt(progress.loaded/progress.total*100)
                    console.log(prog+"%");
                    //undefined
                    this.setState({uploadProgress: prog})
                },
                contentType: file.type, // contentType is optional
            });
        } catch (error) {
            console.log("Error uploading file: ", error);
        }

        //get from S3, works but not the setState
        try {
            const amen = await Storage.get(file.name, { expires: 60 });

            this.setState({
                uri: amen
            })

        } catch (error) {
            console.log("Error file: ", error);
        }

    }

    render() {
        return (
            <div>
                <input type= "file" onChange = { this.onChange } />
                <img src={this.state.uri}/>
                {this.state.uploadProgress && <ProgressBar now={this.state.uploadProgress} label={this.state.uploadProgress + "%"} />}
            </div>
        )
    }
}

一切正常,除了这个:

this.setState({uploadProgress: prog})

我不明白为什么我无法调用状态进度,这是怎么回事?

您正在从不同的执行上下文调用 this 关键字。 progressCallback 中的 this 在其本地执行上下文中搜索名为 setState 的方法,但找不到它。

作为 this related answer describes it,您可以像这样更改代码来引用正确的 this


 async onChange(e) {
      const baseThis = this;
        const file = e.target.files[0];

        try {


            await Storage.put(file.name, file, {
                progressCallback(progress) {
                    const prog = parseInt(progress.loaded/progress.total*100)
                    console.log(prog+"%");
                    baseThis.setState({uploadProgress: prog})
                },
                contentType: file.type, // contentType is optional
            });
        } catch (error) {
            console.log("Error uploading file: ", error);
        }


// other things

}