javascript - React Native - Hook State 更新问题?是同步问题吗?
问题描述
这是这里的代码。基本上它应该接受输入并将其显示在屏幕上的相应部分[电话号码,姓名,地址]。
每次按下“下一步”按钮后,它应该接受输入,将其显示在相应部分的屏幕上,然后将指令 [从“请输入您的电话号码:”更改为“请输入您的姓名:”之后例如,第一次按下按钮]。
它确实在正确的部分显示输入,但它没有正确更改指令。第一次按下“下一步”按钮后,指令保持不变[“请输入您的电话号码:”]。但是在第二次按下按钮后它一直在变化,但现在输入和指令不同步。
我使用计数器在每次按下后更新,它用作指令数组的索引。我尝试跟踪计数器并且它正在正确更新,但不是正在显示的指令。
我刚开始学习 ReactNative,所以请对我放轻松。谢谢:)
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
export default function App() {
var instructions = ['PLEASE ENTER YOUR PHONE NUMBER:', 'PLEASE ENTER YOUR NAME:', 'NOW ENTER YOUR ADDRESS:'];
const [inText, setInText] = useState('');
const [infoList, setInfoList] = useState ([]);
const [counter, setCounter] = useState(0);
const [instruction, setInstruction] = useState(instructions[0]);
const inTextHandler = (textArg) => {
setInText(textArg);
}
const pressNextHandler = () => {
console.log(instructions[counter]);
setInfoList(list => [...list, inText]);
//setInText('');
if (counter >= 2) {
setCounter(0);
setInstruction(instructions[counter]);
} else
{
setCounter(counter + 1);
console.log(counter);
setInstruction(instructions[counter]);
}
}
return (
<View style={styles.screen}>
<Text>
{instruction}
</Text>
<TextInput
placeholder = "ex. (123) 456 7890"
style = {styles.textInput}
onChangeText = {inTextHandler}
value = {inText}/>
<View style={styles.button}>
<Button
title = 'NEXT'
color = 'white'
onPress = {pressNextHandler}/>
</View>
<View style={{marginTop: 10, padding: 10, backgroundColor: 'lightblue', height: 100, justifyContent: 'space-around'}}>
<Text>Phone Number: {infoList[0]}</Text>
<Text>Name: {infoList[1]}</Text>
<Text>Address: {infoList[2]}</Text>
<Text>{counter}</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
paddingVertical: 50,
paddingHorizontal: 50,
backgroundColor: '#f1faee',
height: '100%',
justifyContent: 'center'
},
textInput: {
paddingBottom: 5,
marginTop: 10,
borderBottomColor: 'black',
borderBottomWidth: 1
},
button: {
marginTop: 25,
backgroundColor: '#86D984',
alignItems: 'center',
justifyContent: 'center'
}
});```
[1]: https://i.stack.imgur.com/NcZIf.jpg
解决方案
推荐阅读
- python - 如何使用 python 和 pandas 对多列进行分组
- django - 通过覆盖 __init__ 动态创建表单时,Django 表单验证失败
- android - 启动后在 Android 中运行自定义脚本
- linux - yocto build 中结合了用户空间和设备树配方
- c# - 将控制台应用程序作为后台进程运行@ .NET 5
- winapi - 从自定义 PE 文件中的 dll 导入时找不到过程入口点 MessageBoxA
- javascript - 是否可以从我的服务器对 Amazon S3 存储桶上的文件进行加密和解密
- angular - 是否可以在 routerLink 的 queryParams 中使用常量作为属性名称?
- vue.js - 无法在 markerClusterer 和 Vue3 中读取 null 的属性“__e3_”
- excel - 在 Excel 中循环遍历数组并将设置的范围打印为 PDF