【问题标题】:Unable to reference react 'this' from fetch() callbacks inside event handler无法从事件处理程序内的 fetch() 回调中引用 react 'this'
【发布时间】:2019-05-09 06:55:28
【问题描述】:

无法通过 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

【问题讨论】:

标签: reactjs


【解决方案1】:

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

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

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

【讨论】:

  • 那行得通。非常感谢@ApplePearPerson 的明确答案``` res.json().then((data) => { console.log('API Response: '+JSON.stringify(data)) try { this.setState({devices : data.resp, deviceName: data.deviceName}) ```
猜你喜欢
  • 2013-06-07
  • 2015-06-26
  • 2015-06-17
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多