【发布时间】: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