【问题标题】:Update array in ReactJS [duplicate]在 ReactJS 中更新数组 [重复]
【发布时间】:2017-08-02 04:03:18
【问题描述】:

这就是我在状态变量中的内容

this.state = {
            check: 0,
            places: ["0","0","0","0","0","0","0","0"],
    }
  }

我想要做的是调用一个函数来更新一个位置的期望值。 例如,我正在使用这样的changeValue 函数:

changeValue= (event) => {

        this.setState({
            places[2]: "1",
        });
  }

而且它不起作用。我知道我可以传递一个完全更新的数组,但我需要当前状态的其他值。

【问题讨论】:

标签: reactjs react-jsx


【解决方案1】:

以下是获取当前位置数组其余部分的方法(并复制它以确保不会改变 setState 之外的状态):

changeValue = (event) => {
  const places = this.state.places.slice();
  places[2] = '1';
  this.setState({ places });
}

【讨论】:

    【解决方案2】:

    将此行添加到您的构造函数。

    this.changeValue = this.changeValue.bind(this);
    

    除了此处的其他答案之外,您还需要在构造函数中绑定该函数以使其工作,尤其是当您尝试通过子回调处理事件时。

    【讨论】:

      【解决方案3】:

      setState 以对象为参数,键为状态键。确保传递正确的密钥来更新状态。

      试试这个--->

      changeValue= (event) => {
              this.setState({
                  places: places.map((item, index) => { 
                                  if(index == 2) return 1;
                                  return item;  
                          });
              });   }
      

      【讨论】:

        猜你喜欢
        • 2018-11-04
        • 2016-01-18
        • 2021-04-25
        • 1970-01-01
        • 1970-01-01
        • 2021-08-19
        • 2019-01-01
        • 2021-12-06
        • 2018-04-26
        相关资源
        最近更新 更多