无法引用事件处理程序内部的fetch()回调反应'this'

时间:2019-05-09 06:55:29

标签: reactjs

无法通过带有fetch()响应的this.setState()

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) {
    }

    ...

我希望通过事件处理程序中的回调设置状态 Error screenshot

1 个答案:

答案 0 :(得分:0)

那是因为您尚未将功能callback1绑定到this。因此,在构造函数中,应按与其他函数相同的方式绑定它。

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

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