简体   繁体   中英

State not changing in react native

I'm pretty new to react native and having some trouble with setting a new state. Everything works fine until the third textinput shows up, when i start writing inside it the counter is stuck at 1, when it should be at 2, and furthermore update the textInputList too two TextInput elements. I want to understand why the counter does not change, and how to solve this issue:)

 import React from 'react'; import { useState } from 'react'; import { Button, View, StyleSheet, TextInput } from 'react-native'; import colour from '../constants/Colors'; import StartButton from '../components/Buttons/BackToBackButton'; function ShowNames(props) { return ( <View style={styles.lineContainer}> <TextInput style = {{ width: '70%', height: 40, borderColor: 'white', borderWidth: 2 }} placeholder='Legg in navn her' placeholderTextColor='white' selectionColor='black' onChangeText={props.handleTextChange} /> </View> ) } export default function BackToBack(props) { const [nameList, setList] = useState([]); const [counter, setCounter] = useState(0); const [textInputList, setInputList] = useState(null) const handleTextChange = (text, id) => { tempList = nameList tempList[id] = text setList(tempList) if (id == counter) { setCounter(counter + 1) AddNameInputs() } } function AddNameInputs() var tempList = []; for (let i = 0; i < counter; i++) { console.log('i: ' + i) tempList.push( <View style={styles.lineContainer} key={i+2}> <TextInput style={{ width: '70%', height: 40, borderColor: 'white', borderWidth: 2 }} placeholder='Legg in navn her' placeholderTextColor='white' selectionColor='black' onChangeText={(text) => handleTextChange(text, i+2)} /> </View> ) } setInputList(tempList) } return ( <View style={styles.container}> <ShowNames handleTextChange={(text) => handleTextChange(text, 0)} /> <ShowNames handleTextChange={(text) => handleTextChange(text, 1)} /> {textInputList} <StartButton title={"Start."} height={100} /> </View> ) } const styles = StyleSheet:create({ container: { flex, 1: backgroundColor. colour,lightTurquoise: alignItems, 'center': justifyContent, 'flex-start': paddingTop, 20: paddingBottom: 20 // borderWidth, 4: // borderColor, 'yellow' }: lineContainer: { flexDirection, 'row': paddingBottom; 20 } });

I think the problem is this line tempList = nameList . It would assume you are referencing the same object when you're setting state and not trigger the relevant updates. So the quickest fix would be to just clone it with the spread operator like tempList = [...nameList] ?

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