简体   繁体   中英

how to pass data from child component to state of parent component react native?

PARENT

import Child from '../Child';

const Parent = () => {
  const [inputValue, setInputValue] = useState('');

  const handleChild = (value) => {
    setInputValue(value);
    console.log('VALUE:', value);
    console.log('STATE:', inputValue);
  };
  console.log(inputValue); //shows the same as VALUE
  return (
    <View>
      <Child passInputValue={handleChild} />
    </View>
  );
};

Child

const Child = ({passInputValue}) => {
  const [input, setInput] = useState('');
  return (
    <View>
      <TextInput value={input} onChangeText={(text) => setInput(text)} />
      <TouchableOpacity onPress={() => passInputValue(input)}>
        <Text>SEND DATA TO PARENT</Text>
      </TouchableOpacity>
    </View>
  );
};

When I fill the input and then press the button, the console shows me in VALUE: the current value of the input and in STATE the previous value of input

"CLICK 1"

VALUE: 'WHATEVER'

STATE: ''

"CLICK 2"

VALUE: 'WHATEVER'

STATE: 'WHATEVER'

what I need is that when I click, execute realm and save the value of inputValue, but it always saves the previous value

I would appreciate any help:)

change as follows

<Child passInputValue={(value)=>handleChild(value)} />

What's happening here is that React is executing the lines of handleChild asynchronously rather than in order. You call setInputValue(value) to change the inputValue , but before the state gets updated console.log('STATE:', inputValue) has already begun executing with the previous value. The update is happening correctly, but your log is printing the value before the update rather than after.

That's why you see the console.log(inputValue) statement which is outside of the function printing the correct value. This function is run when the component re-renders, which happens after the state updates, so you are getting the updated value here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM