【问题标题】:setState is not working properly in react nativesetState 在本机反应中无法正常工作
【发布时间】:2019-08-22 10:30:38
【问题描述】:

我想创建一个包含多个对象的对象。数据是这样的

dataList = [{inputFieldId: 1, dataField:{...}, data: '120'}, {inputFieldId: 2, dataField:{...}, data: '120'} ]

什么是这样想要的。

res = [{1: '120'}, {2: '120'}]

我为此编写了一个代码,但它只给了我最后一个对象数据。

  constructor(){
  super()
  this.state = {
  inputValue:{},
  datalist = [],
  }
  }


   async componentWillMount(){
     for(var key in dataList){
        this.setState({
           inputValue: {
             ...this.state.inputValue,
             [dataList[key].inputFieldId]: dataList[key].data
          }
      })
  }     
}

code output = { 2: '120'}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您可以尝试如下代码:

    constructor(){
      super()
      this.state = {
        inputValue: {},
        datalist = [],
      }
    }
    
    
    async componentWillMount() {
      const inputValues = [];
      for(var key in dataList) {
        inputValues.push({[dataList[key].inputFieldId]: dataList[key].data});
      }
      this.setState({ inputValue: inputValues });
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多