无法从事件处理程序中的 fetch() 回调中引用反应"this"



无法使用fetch((响应

无法进入此.setState((

dod fetch((在表单内提交事件处理程序,但无法从fetch((回调设置状态

TypeError:无法读取未定义的

的属性'setstate'
    ...
    constructor(props) {
        super(props);
        this.state = { deviceName: '', devices: [] };
        this.handleChange = this.handleChange.bind(this);
        this.handleSearchDevice = this.handleSearchDevice.bind(this);
    }
    componentWillMount() {
        this.setState({
            devices: this.props.devices
        });
    }
    componentDidMount() {
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            devices: nextProps.devices
        });
    }
    handleChange(event) {
        this.setState({deviceName: event.target.value });
    }
    handleSearchDevice(event) {
        console.log('Searching '+this.state.deviceName)
        event.preventDefault();
        //Get data from API
        const url = 'device/name'
        const data = { deviceName:this.state.deviceName}
        fetch(url, { method: 'POST',
            body: JSON.stringify(data),
            headers:{ 'Content-Type': 'application/json' }
        }).then(res => {
            res.json().then(function(data) {
                console.log('API Response: '+JSON.stringify(data))
                try {
                    this.setState({devices: data.resp, deviceName: data.deviceName})
                } catch(err) {
                    console.log('catch ' + err.stack)
                    this.callback1(data)
                }
            });
        }).catch(error => {
            console.error('Error:', error)
        }).then(response => {
            console.log('Success:', response)
        });
    }
    callback1(data) {
        this.setState({devices: data.resp, deviceName: data.deviceName})
        console.log(data)
    }
    render() {
        ...
    }
    componentDidUpdate(prevProps) {
    }
    ...

我希望从事件处理程序内的回调设置状态错误屏幕截图

那是因为您没有将函数 callback1绑定到 this。因此,在您的构造函数中,您应该像绑定其他功能一样绑定它。

另一种方法是使callback1成为箭头函数,以便不必绑定它。看起来像这样:

callback1 = () => {
    this.setState({devices: data.resp, deviceName: data.deviceName})
    console.log(data)
}

最新更新