我的状态中有一个名为 purchaseItems 的数组,其值当前是硬编码的。我有另一个名为 priceArray 的数组,我在状态下初始化为空,我一直在尝试在 componentDidMount() 中修改它,使其具有 purchaseItems 数组的长度并用零填充。我一直在尝试做的方法是获取 purchaseItems 的长度,创建名为 newArray 的 priceArray 的副本,使用 for 循环将零推入 newArray 直到它具有与 purchaseItems 相同的长度,然后通过 setState 将 newArray 附加到 priceArray。但是,当我通过 console.log 检查 priceArray 时,它仍然为空。为什么会这样?我将附上下面的代码。注意:我计划最终从数据库中填充 purchaseItems,因此 purchaseItems 数组的长度并不总是相同,所以这就是我不硬编码的原因,比如说,一个长度为 5 的充满零的数组priceArray 如果 purchaseItems 的长度为 5。我所在州的代码: state = {}; constructor(props) { super(props); this.state = { purchaseItems: [redacted], priceArray: [], }; }我的 componentDidMount() 中的代码: componentDidMount() { console.log("Purchase Items: " + JSON.stringify(this.state.purchaseItems)); const numItems = this.state.purchaseItems.length; console.log("numItems: " + numItems); var newArray = this.state.priceArray.slice(); console.log("initialized newArray: " + JSON.stringify(newArray)); var i; for (i = 0; i < numItems; i++) { newArray.push(0); } console.log("populated newArray: " + JSON.stringify(newArray)); this.setState({ priceArray: [...this.state.priceArray, newArray] }); console.log("priceArray: " + JSON.stringify(this.state.priceArray)); }终端:Purchase Items: [redacted]numItems: 6initialized newArray: []populated newArray: [0,0,0,0,0,0]priceArray: []
1 回答

富国沪深
TA贡献1790条经验 获得超9个赞
priceArray
正确设置状态
this.setState({ priceArray: [...this.state.priceArray, ...newArray] },()=>console.log(his.state.priceArray));
您也可以在一行中完成整个操作
this.setState({priceArray:(new Array(this.state.purchaseItems.length)).fill(0))},()=>console.log(his.state.priceArray))
添加回答
举报
0/150
提交
取消