【问题标题】:Why does the first iteration of my update to an array in state does not appear? It will only appear after the second iteration?为什么我对状态数组的更新的第一次迭代没有出现?它只会在第二次迭代后出现?
【发布时间】:2020-04-04 23:28:22
【问题描述】:

我在 Main.js 的 state 中定义了一个数组 postArray。

    this.state ={
        step: 1, 
        // welcome
        qNumber:1,
        accountNumber:'',
        amount:'',
        txNumber:1,
        postArray : []
    }

我在 Main.js 上还有一个函数,它将新的数组元素插入到 postArray 中:

insertTx =() => {
    // save transaction to array state
    // create copy of the array
    const copyPostArray = Object.assign([],this.state.postArray)
    // insert one element into the array
    copyPostArray.push({
        txNumber: this.state.txNumber+"-"+this.state.accountNumber,
        qNumber : this.state.qNumber,
        accountNumber : this.state.accountNumber,
        amount :   this.state.amount
    })
    // save the values back to array state
    this.setState({
        postArray:copyPostArray
    })
    console.log(this.state.postArray)
    console.log(this.state.txNumber)
    console.log(this.state.qNumber)
    console.log(this.state.accountNumber)
    console.log(this.state.amount)
}

在 CashDeposit.js 上,每当我调用下面的 InsertTx 函数时,都会更新 postArray:

continue = e => {
    e.preventDefault();
    this.props.nextStep();
    //increment the txNumber
    // this.props.incTxNumber();
    this.props.insertTx();

在 console.log 上查看 postArray,它在第一次迭代时显示一个空数组。但是对于第二次迭代,它将显示第一次的值,第三次迭代将显示第二次的值,依此类推。为什么它不更新当前值?

【问题讨论】:

  • 您可以尝试将async .. await 添加到您的函数中,例如insertTx = async() => { ... await this.setState({ .... }) .... } .. 在setstate 之前使用await ..
  • @Maniraj,没有理由在 setState 中使用 async 和 await。

标签: arrays reactjs


【解决方案1】:

setState 不会立即发生。在下一次渲染发生之前,状态将始终是相同的值。如果你更新状态,那么在同一个循环引用状态下,你会得到旧的状态。如果您执行以下操作,这会使您看起来落后于:

this.setState(newValues) 
console.log(this.state) // old values

确保在引用状态时不依赖其他函数的 setState。这就是 hooks 和 useEffect 派上用场的地方。

【讨论】:

    【解决方案2】:

    您看到的问题是由setState does not set the state immediately 引起的,您可以将其视为异步操作。因此,当您尝试记录状态值时,您将获得旧值,因为状态尚未更改。

    为了访问新的状态值,您可以将回调作为第二个参数传递给setStatethis.setState(newState, updatedState => console.log(updatedState))

    【讨论】:

      【解决方案3】:

      这是因为setState() does not immediately update state。在下次调用 render() 之前,您不会看到更新的状态。由于 React 是如何协调的,这非常快,因为 React 不会尝试构建 DOM,直到所有的 setState() 调用都被抖掉。但这也意味着,虽然您无法立即在控制台中看到新状态,但您可以放心,您最终会在它出现在浏览器中之前看到它。

      但是,这确实意味着您需要确保在代码中处理了初始状态条件。例如,如果您没有在构造函数中设置状态,那么您将至少需要在其中进行渲染而不会引发未定义状态的错误。

      【讨论】:

        猜你喜欢
        • 2016-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        • 2011-10-31
        • 2023-04-02
        • 2018-11-25
        相关资源
        最近更新 更多