【问题标题】:React-Native: Unable to set size of an array in the state to the size of another array in the stateReact-Native:无法将状态中数组的大小设置为状态中另一个数组的大小
【发布时间】:2020-04-27 19:35:18
【问题描述】:

我的状态中有一个名为 purchaseItems 的数组,其值当前是硬编码的。

我有另一个名为 priceArray 的数组,我在状态下初始化为空,我一直在尝试在 componentDidMount() 中对其进行修改,使其具有 purchaseItems 数组的长度并用零填充。

我一直在尝试的方法是获取 purchaseItems 的长度,创建名为 newArray 的 priceArray 的副本,使用 for 循环将零推入 newArray 直到它与 purchaseItems 具有相同的长度,然后将 newArray 附加到 priceArray通过 setState。

但是,当我通过 console.log 检查 priceArray 时,它仍然为空。为什么会这样?下面我附上代码。

注意:我计划最终从数据库中填充 purchaseItems,因此 purchaseItems 数组的长度并不总是相同,所以这就是我不硬编码的原因,例如,一个长度为 0 的数组如果 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: []

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    正确设置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))
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 2019-07-17
      • 2021-02-22
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多