为什么我不能在我的代码中使用 setState 值?

why I can not use setState value in my code?

我正在尝试创建一个新数组,当我使用 console.log 检查 this.state.allColor 时,我可以看到值发生了变化,但是当我使用 this.state.allColor 的相同值时在创建新数组时,它不起作用:

onValueChange = (e) => {
    const allColor=e.target.value;
    this.setState({allColor})
    const boxes = new Array(this.state.allColor).fill().map(this.randomColor,this)
    this.setState({boxes})
};

这也行不通

onValueChange = (e) => {
    const allColor = e.target.value;
    const boxes = new Array(this.setState({allColor})).fill().map(this.randomColor,this)
    console.log(boxes)
};

这也不行

onValueChange = (e) => {
    const allColor = e.target.value;
    const allBoxes = this.setState({allColor})
    const boxes=new Array(allBoxes).fill().map(this.randomColor,this)
    console.log(boxes)
};

如果我使用 console.log,this.state.allColor 的值每次都会正确更改,但我不能在新数组中使用该值。

但这会起作用

onValueChange=(e) => {
    const totalNumber = 4
    const boxes=new Array(totalNumber).fill().map(this.randomColor,this)
    this.setState({boxes})
};

setState 是一个 asynchronous 操作,因此您无法立即访问其最新值。

setState() does not always immediately update the component

此外,每当您在组件中调用 setState 时,都会触发一个新的 render。所以最好只更新一次组件的状态,以节省一点性能。

onValueChange= (e) => {
  const allColor = parseInt(e.target.value, 10)

  this.setState({
    allColor,
    boxes: new Array(allColor).fill().map(this.randomColor,this)
  })
};