0
votes

why useState auto update? I'll press button and not showing textinput. but I can save file without change. textinput will be showing. sorry my bad english

import React, { useState,useEffect } from 'react'; import {Text, TextInput, View, Button,} from 'react-native';

    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;
1

1 Answers

0
votes

I have a few suggests to make your code better.

  1. Don't change state value if not in use 'setState'. This is false by nature and causes errors.

      addTextInput = (key) => {
      textInput.push([<TextInput style={{backgroundColor :'#7ACB4A',marginTop:10}} key={key} />]);
      settextInput(textInput);
      console.log(textInput); 
      }
    
  2. State merely contains value, it should not contain different things. You should return TextInput in your map function.

  3. I try rewrite your code, sorry because my english. Hope help you

code:

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>
)

}