我的状态中有一个名为purchaseItems的数组,其值当前为硬编码的。我还有一个名为priceArray的数组,该数组在状态中初始化为空,并且我一直试图在componentDidMount()中对其进行修改,以使其具有purchaseItems数组的长度并用零填充。我一直在尝试的方法是获取purchaseItems的长度,创建一个名为newArray的priceArray的副本,使用for循环将零推入newArray,直到其长度与purchaseItems相同,然后通过setState将newArray附加到priceArray 。但是,当我通过console.log检查时,priceArray仍然为空。为什么会这样呢?我将在下面附加代码。
注意:我打算最终从数据库中填充purchaseItems,所以purchaseItems数组的长度将不总是相同,因此这就是为什么我不对长度为零的数组进行硬编码的原因如果purchaseItems的长度为5,则priceArray为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: 6
initialized newArray: []
populated newArray: [0,0,0,0,0,0]
priceArray: []
答案 0 :(得分:0)
正确设置class Lesson_15_Activity{
public static void sortAndPrint(String [] list){ //cant change
for (int pos = 0; pos < list.length-1; pos++){
for (int k = 0; k <= pos; k++){ //
if (list[k].compareTo(list[pos]) < 0){
list[pos] = list[k];
}
}
}
for (int a = 0; a < list.length-1; a++){
System.out.println(list[a]);
}
}
public static void main(String[] args) {
String [] list = { "against" , "forms" , "belief" , "government" , "democratic" , "movement" , "understanding"};
sortAndPrint(list);
//^this is where i get the error
}
}
的状态
priceArray
您还可以一行完成全部操作
this.setState({ priceArray: [...this.state.priceArray, ...newArray] },()=>console.log(his.state.priceArray));