我对setState
的调用在fetch
的then
中不做任何事情。
类声明如下:
export default class QuestionHolder extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
completed: false,
revealAnswer: false,
selectedAlternative: undefined,
submitting: false,
explanation: 'philosophy',
}
console.log('props', props)
console.log('state', this.state)
}
fetch(`/questions/${this.question.id}/submit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
chosen: this.state.selectedAlternative.id,
}),
})
.then(response => response.json())
.then(data => {
console.log('data', data)
console.log('state before', this.state)
this.setState({
explanation: 'phil says so'
})
console.log('state after', this.state)
})
fetch
工作得很好(返回data
和200等-这是我正在更新的遗留代码),但是对console.log
的调用显示this.state
从未从构造函数中设置的值更改。
状态更新可能是异步的,在设置后立即读取它将无法提供正确的结果。
检查状态变化的正确位置是将callback作为第二个参数传递给setState
方法
this.setState({
explanation: 'phil says so'
},() => {
console.log('Set the explanation state successfully')
})
或使用componentdiduupdate生命周期方法
componentDidUpdate(prevProps, prevState){
if (prevState.explanation !== this.state.explanation) {
console.log('Set the explanation state successfully')
}
}