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

时间:2017-12-18 14:55:47

标签: reactjs fill setstate

我正在尝试创建一个新数组,当我使用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})
};

1 个答案:

答案 0 :(得分:3)

setStateasynchronous操作,因此您无法立即访问其最新值。

  

setState()并不总是立即更新组件

此外,无论何时在组件中呼叫setState,都会触发新的render。因此,最好只更新组件的状态一次,以节省一点性能。

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

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