首页 > 解决方案 > 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

标签: javascriptreactjsreact-native

解决方案


推荐阅读