【发布时间】: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。