使用地图反应对象的setState数组不起作用?

Ali*_*gan 6 javascript ecmascript-6 reactjs

我在执行setState更改对象嵌套数组的值时遇到问题。下面的代码假设将id 2的问题更改为答案:true,但是没有,这是怎么回事?

this.state = {
  questions: [
    {
      id: 1,
      answer: ''
    },
    {
      id: 2,
      answer: ''
    },
  ]
}
//I have a click event somewhere
this.setState(
  {
    questions: this.state.questions.map(q => {
      if (q.id === 2) {
        return {
          ...q,
          answer: true
        }
      } else {
        return { ...q }
      }
    })
  },
  console.log(this.state.questions[1]) // did not see id of 2 being changed to true?
)
Run Code Online (Sandbox Code Playgroud)

Fin*_*sse 4

console.log(this.state.questions[1])行在该行执行之前执行this.setState,这就是旧状态打印到控制台的原因。您应该将该行放在函数内以延迟执行:

this.setState(..., () => console.log(this.state.questions[1]));
Run Code Online (Sandbox Code Playgroud)

另外,如果更改的状态是从当前状态派生的,建议使用函数作为第一个参数,因为 React 不会立即应用新状态,因此this.state当 React 应用新状态时可能会过时:

this.setState(state => ({
  questions: state.questions.map(q => {
    if (q.id === 2) {
      return {...q, answer: true};
    }
    return q;
  })
}), () => {
  console.log(this.state.questions[1]);
});
Run Code Online (Sandbox Code Playgroud)