簡體   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