简体   繁体   中英

Change array object value in react native with textInput and function component

Hello guys I wanna ask about change Array Value when I type in text input in react native

const [rad, setRad] = useState([
  { value: 'a', status: false, title: 'ab },
  { value: 'b', status: false, title: 'ac' },
  { value: 'c', status: false, title: 'ad' },
]);


<TextInput 
  numberOfLines={2} 
  placeholder="note"
  onChangeText={(text) => setRad([...rad[3], { value: text }])}
/>

but when I type an error screen comes up and the message 'Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method'

What should I do?

The initial state is an array of length 3, ie with indices 0, 1, and 2, so attempting to spread ...rad[3] is the code attempting to spread the fourth element, which is an undefined value.

You likely meant to spread the previous rad state array instead into the new array reference and append the new text value. When updating arrays in React state it's recommended to use a functional state update to ensure updating from the previous state and not the value of state closed over in any callback/handler scopes.

<TextInput 
  numberOfLines={2} 
  placeholder="note"
  onChangeText={(text) => setRad(rad => [...rad, { value: text }])}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM