reactjs 在react-native中,如何更新数组中的嵌套值?

5rgfhyps  于 2023-03-29  发布在  React
关注(0)|答案(1)|浏览(124)

用户使用react-native SelectDropdown为数据输入表单选择所需的类型。

{/* Select Dropdown creates a TextInput */}
 <SelectDropdown data={types} onSelect={handleSelect} placeholder="Add a field" />

 
 const [needsAnotherInput, setNeedsAnotherInput] = useState(false)
 //Sets the needed type
 const [neededInput, setNeededInput] = useState ([]);  
 //SelectDropdown data
 const types = ['Electric', 'Gas', 'Water'];

 //sets the addedField array to be sent to the Server
 const [addedField, setAddedField] = useState([]);

  //Creates needed input
  const handleSelect = (type) =>{
    setNeedsAnotherInput(true);
    setNeededInput([...neededInput, type]);
    setAddedField([...addedField,  {field: type, read: null}]);
  }

  //Here is where the read gets added to the state object addedField
  const handleAddedFields = (read) =>{
    setAddedField({...addedField, read: read})
  }

TextInput按预期返回

{needsAnotherInput ? neededInput.map((needed =>{
        return <>
        <TextInput 
        key={needed} 
        value={addedField} 
        name={needed} 
        onChangeText={handleAddedFields} 
        style={styles.textInput} 
        placeholder={needed} />
        </>
      })): null}

我的问题在于当我试图更新对象内部的“读取”值时

addedField: [
    { field: 'Electric', read: null },
    { field: 'Gas', read: null },
    { field: 'Water', read: null }
  ]
}

下面是将数据发送到服务器的提交函数

//Currently the submit button sends the location to the server to to be stored in MongoDB along with the user token for AUTH
  const handleSubmit = () => {
    const fetchReq = async () => {  
      const requestOptions = {
        method: 'post',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({addedField})
      }
      //Enpoint just console.logs the request body 
      fetch('http://10.0.2.2:5000/test', requestOptions)
    }
    fetchReq();
  }

“read”值没有正确更新,这里是发送到服务器的对象

addedField: {
    '0': { field: 'Electric', read: null },
    '1': { field: 'Gas', read: null },
    '2': { field: 'Water', read: null },
    read: '123'
  }
}
deyfvvtc

deyfvvtc1#

我可能误解你的意思了,但我觉得你应该试试:

const handleAddedFields = (read , index) =>{
  setAddedField(prev=>prev.map((field,i)=>{
    if(index === i){
      return {...field, read: read}
    }
    return field
  })
}
//...
{needsAnotherInput ? neededInput.map((needed,i) =>{
    return <>
    <TextInput 
    key={needed} 
    value={addedField} 
    name={needed} 
    onChangeText={(val,i)=>handleAddedFields(val, i)} 
    style={styles.textInput} 
    placeholder={needed} />
    </>
  })): null}

相关问题