【问题标题】:React Native - Dynamic forms and updating state that has an array of objectsReact Native - 具有对象数组的动态表单和更新状态
【发布时间】:2020-05-25 08:28:14
【问题描述】:

如何处理动态显示的多个输入字段并根据索引更新输入字段状态。

const [state, setState] = useState[{value1: '',  value2: ''}]

const handleValue1 = (index, value) => {
  setState(prevObj => ({
    ...prevObj[index],
    value1: value,
  }));
  console.log(state);
}

const handleValue2 = (index, value) => {
  setState(prevObj => ({
    ...prevObj[index],
    value2: value,
  }));
  console.log(state);
}

return (
  <FlatList
    data={DATA}
    renderItem={({item, index}) => (
      <TextInput
        onChangeText={e => handleValue1(index, e)}
        value={state.value1}
      />

      <TextInput
        onChangeText={e => handleValue2(index, e)}
        value={state.value2}
      />
   />
)

可能有多个 TextInput 对,具体取决于 DATA,我如何动态更新最终我将拥有的值:

[0]: {
  value1: 'some value',
  value2: 'another value',  
},
[1]: {
  value1: 'some value from another update',
  value2: 'another value from another update again',  
}

问题是,如果我更新 1 个 TextInput,所有 TextInput 字段都将更新为相同的数字,然后更新的状态会擦除数组,只保留 1 个对象对。

【问题讨论】:

    标签: arrays reactjs react-native object react-hooks


    【解决方案1】:

    刚刚想通了……

    const handleValue1 = (index, value) => {
      state[index] = {...state[index], ['value1']: value};
      /*setState(prevObj => ({
        ...prevObj[index],
        value1: value,
      }));*/
      console.log(state);
    }
    
    const handleValue2 = (index, value) => {
      state[index] = {...state[index], ['value1']: value};
      /*setState(prevObj => ({
        ...prevObj[index],
        value2: value,
      }));*/
      console.log(state);
    }
    

    如果有其他人可能感兴趣。

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 2020-11-13
      • 2020-10-21
      • 2019-12-15
      • 2020-05-26
      相关资源
      最近更新 更多