Preact/React和获取后的设置状态



我对setState的调用在fetchthen中不做任何事情。

类声明如下:

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

最新更新