【问题标题】:How to pass state object from child to parent in React-Native如何在 React-Native 中将状态对象从子级传递给父级
【发布时间】:2021-04-25 15:43:10
【问题描述】:

我正在调用 Api 以获取地址详细信息,例如 address_line1、address_line2、区域、城市、国家/地区、密码。

在子组件中,我只显示 address_line1、address_line2、country、pincode。

下面是我的子组件

的sn-ps
const [options, setOptions] = React.useState([]);

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

然后我将结果映射到我的应用程序中:

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

我的 cityTile 组件:

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

当用户点击屏幕上显示的结果时,它应该返回到上一个屏幕,这是我的父组件。我在cityTile 组件上的onPress 给出了导航。

下面是我的父组件的sn-ps:

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]);
};

如您所见,我使用useEffect 来更新父组件中第一次打开页面时的状态。

但是当子组件发生变化时,我不知道如何更新父组件中的状态。

我知道我必须将状态从孩子传递给父母,但我无法弄清楚如何做到这一点。

请帮忙,这是我的应用程序的最后一个功能,我对如何做到这一点感到压力很大。

【问题讨论】:

  • 你需要使用 useContext() 或 Redux 之类的东西将数据从子组件传递到父组件
  • 为此目的使用 redux
  • @FazalUrRehmanFazal 我必须在没有 redux 的情况下这样做
  • 然后在父组件的父组件中创建profileState,然后在父组件中创建函数并将此函数作为道具传递给子组件,其中从子状态更新父组件状态在父组件中: const [profileState, setProfileState]=useState getDatafromChild(val){ setProfileState(val) }) render(){ return();在子组件中:props.sendDate(result.data.profileDate)

标签: react-native react-native-android react-native-ios


【解决方案1】:

将一个函数从父级传递给子级,然后将子级的状态作为参数传递给该函数,以便在您编码时更改父级中的状态

在父组件中:

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

在子组件中:

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

【讨论】:

  • 但这不会导致运行 useEffect bcz useEffect 在 profileState.loading 更改时有条件地运行
猜你喜欢
  • 2020-09-09
  • 2016-09-26
  • 2020-12-31
  • 2018-09-17
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 2016-05-13
相关资源
最近更新 更多