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

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

在尝试使用 S3 中的 async 函数获取一些数据时出现此错误:TypeError: Cannot read properties of undefined (reading 'setState')

我想做的是从电脑上选择一个文件,将其上传到 S3 并在我的 dom.

中呈现
class Dashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = { uri: "" };
    }

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

        //upload to S3, works great
        try {
            await Storage.put(file.name, file, {
                contentType: "image/png", // 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 });
            console.log('amen: ', amen); //correct output data

            //the error is here!
            this.setState({
                uri: amen
            })

            console.log('after: ', this.state.uri); //not output on console

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

    }


    render() {
        return (
            <div>
                <input type= "file" onChange = { this.onChange } />
                <img src={this.state.uri}/>
            </div>
        )
    }
}

一切正常,不是这个:

this.setState({ uri: amen })

为什么,怎么了?

好的,我找到了解决办法。 使用箭头函数,如:

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

    //upload to S3
    try {
        await Storage.put(file.name, file, {
            contentType: "image/png", // contentType is optional
        });
    } catch (error) {
        console.log("Error uploading file: ", error);
    }

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

        this.setState({
            uri: amen
        })

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

}

如果您按以下方式声明函数

    onChange = (e) => {
             ....rest of your code...
         this.setState({
                uri: amen
            })
    }

它工作正常。

如果你想用另一种(旧的,如果我没记错的话)方式来做,那么你需要将函数绑定到子组件的 class,即 onChange 处理程序class“看到”它:

    constructor(props) {
        super(props);
        this.state = { uri: "" };
    }

最后,您可以在 return 组件内部进行直接绑定

        return (
                <input type="file" onChange={ this.onChange.bind(this)} />
        );

本期功劳: https://whosebug.com/posts/69687421/edit 刚刚为你做了正确的匹配:)