【问题标题】:React Native useState not auto Updating?React Native useState 不自动更新?
【发布时间】:2021-01-07 03:55:48
【问题描述】:

为什么要使用状态自动更新?我将按下按钮而不显示文本输入。但我可以保存文件而无需更改。文本输入将显示。对不起我的英语不好

从 'react' 导入 React, { useState,useEffect }; 从 'react-native' 导入 {Text, TextInput, View, Button,};

    const Test = ({navigation}) => {
        const [textInput, settextInput] = useState([]);

        useEffect(() => {
        addTextInput = (key) => {
          
          textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
        
          settextInput(textInput);
          console.log(textInput); 
          }
        },[textInput]);
          return(
            <View>
            <Button title='+' onPress={() => 
               addTextInput(textInput.length)} />
            {textInput.map((value, index) => {
              return value
            })}
            <Text>{textInput.length}</Text>
          </View>
          );

    }
    export default Test;

【问题讨论】:

    标签: react-native


    【解决方案1】:

    我有一些建议可以让你的代码变得更好。

    1. 如果不使用“setState”,请不要更改状态值。 这本质上是错误的,会导致错误。

        addTextInput = (key) => {
        textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
        settextInput(textInput);
        console.log(textInput); 
        }
      
    2. 状态仅仅包含值,它不应该包含不同的东西。您应该在 map 函数中返回 TextInput。

    3. 我尝试重写你的代码,对不起,因为我的英语。希望能帮到你

    代码:

    const [textInput, setTextInput] = React.useState(['1', '2'])
    const addTextInput = (key: string) => {
        const tempInput = textInput.concat([key])
        setTextInput(tempInput)
    }
    return (
        <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
            <Button title="+" onPress={() => addTextInput(textInput.length.toString())} />
            {textInput.map((value, index) => {
                return (
                    <TextInput style={{ backgroundColor: '#7ACB4A', marginTop: 10, width: '70%' }} key={index + ''} />
                )
            })}
            <Text>{textInput.length}</Text>
        </View>
    )
    

    }

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2022-08-14
      • 1970-01-01
      • 2021-03-06
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      相关资源
      最近更新 更多