简体   繁体   中英

How to pass state object from child to parent in React-Native

I am making an Api call to get address details, like address_line1, address_line2, area, city, country, pincode.

In the child component I am only showing address_line1, address_line2, country, pincode.

Below are the snippets from my child component

const [options, setOptions] = React.useState([]);

if (result.status === 200 && result.data.status === 'success') {
      setOptions(result.data.data);
    }

Then I am mapping the result in my app:

<ScrollView showsVerticalScrollIndicator={false}>
  {options.map((i, index) => cityTile(i))}
</ScrollView>;

my cityTile component:

const cityTile = (item) => {
  return (
    <TouchableOpacity
      onPress={() => {
        // what to do here
          navigation.goBack();
      }}>
      <CityTile >
        <Text>
          {item.address_line1}, {item.address_line2}, {item.country},{" "}{item.postCode}
        </Text>
      </CityTile>
    </TouchableOpacity>
  );
};

When a user clicks on a result displayed on the screen, then it should go back to previous screen, which is my parent component. I have given navigation at onPress on cityTile component.

Below are the snippets from my parent component :

const AddressSection = ({navigation, dispatchAction, profileState}) => {
  const [stateVar, updateStateVar] = useState({
    address_line_1: '', address_line_2: '', area: '', city: '', pincode: '', country: '',
  });
  React.useEffect(() => {
    if (!profileState.loading && !profileState.error) {
      updateStateVar({
        ...stateVar,
        address_line_1: profileState.address.address_line_1,
        address_line_2: profileState.address.address_line_2,
        area: profileState.address.area,
        city: profileState.address.city,
        country: profileState.address.country,
        pincode: profileState.address.pincode,
      });
    }
  }, [profileState.loading]);
};

As you can see I am using useEffect to update the state when page opens for the first time in parent component.

But I don't know how to update the states in parent component when changes happens in child component.

I know that I have to pass state from child to parent, but I am not able to figure out how to do this.

Please help, this is the last functionality of my app, and I am all stressed out on how to do this.

Pass a function from parent to child and then pass the state from child as argument to that function which in order will change the state in parent as you code

In Parent Component:

getDatafromChild(val){
    console.log(val);
}
render(){
 return(<Child sendData={this.getDatafromChild}/>);
}

In Child Component:

callBackMethod(){
   this.props.sendData(value);
 }

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