【发布时间】:2020-04-16 16:04:17
【问题描述】:
我希望我的应用程序显示一个文本输入,当您开始在第一个输入时,应用程序将显示第二个文本输入,依此类推... 下面我的代码的问题是计数器始终保持为零。我已经测试了线程通过console.log()进入if语句,但是计数器没有改变,我开始发疯了
import React from 'react';
import { useState, useEffect } from 'react';
import { Button, View, StyleSheet, TextInput, FlatList } 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([{key: '2.9204739', value: <ShowNames handleTextChange={(text) => handleTextChange(text, counter)} />}])
const handleTextChange = (text, id) => {
tempList = nameList
tempList[id] = text
setList(tempList)
console.log("ID: " + id)
console.log("Counter: " + counter)
if (id == counter) {
console.log("yo")
setCounter(counter + 1)
AddNameInputs()
}
console.log(nameList)
}
function AddNameInputs() {
const temp =
<View style={styles.lineContainer}>
<TextInput
style={{ width: '70%', height: 40, borderColor: 'white', borderWidth: 2 }}
placeholder='Legg in navn her'
placeholderTextColor='white'
selectionColor='black'
onChangeText={(text) => handleTextChange(text, counter)}
/>
</View>
setInputList([...textInputList, {key: Math.random().toString(), value: temp}])
}
return (
<View style={styles.container}>
<FlatList data={textInputList} renderItem={itemData => itemData.item.value} />
<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
}
})
请帮帮我:)
【问题讨论】:
-
id == counter 永远不会为真,因为 id 被定义为 counter + 1
-
AddNameInputs的目的是什么?为什么要将组件存储在temp中? -
@TheoWckr 是的,我知道,我只写它是因为计数器不会变为 1,问题是计数器保持在 0
-
@goto1 AddNameInputs 是一个功能,用于将新的文本输入组件添加到我的平面列表中
-
啊,我明白了,setCounter 是异步的,所以当你调用
AddNameInputscounter 时,可能仍然等于 0,我会尝试一下
标签: reactjs react-native react-hooks state use-state