繁体   English   中英

State 在本机反应中没有变化

[英]State not changing in react native

我对本机反应很陌生,并且在设置新的 state 时遇到了一些麻烦。 一切正常,直到第三个 textinput 出现,当我开始在其中写入时,计数器停留在 1,当它应该在 2 时,并且还更新 textInputList 两个 TextInput 元素。 我想了解为什么计数器不改变,以及如何解决这个问题:)

 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 } });

我认为问题在于这一行tempList = nameList 假设您在设置 state 并且不触发相关更新时引用相同的 object。 所以最快的解决方法是用像tempList = [...nameList]这样的扩展运算符克隆它?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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