【问题标题】:Props not being passed - React Native道具未通过 - React Native
【发布时间】:2018-04-24 09:47:06
【问题描述】:

我正在使用react-native-modalbox 来显示模式并保存数据作为结果。

当我保存数据时,我的模态可以访问父平面列表,因此我可以正确调用 getData() 函数,并且平面列表反映了最新更新:

模态 - saveItem() 在按下保存按钮时执行。

  saveItem = async () => {
    ...
      this.props.parentFlatList.getData();
      this.props.progress.getData(); //This function call returns an error
      this.closeModal();
  };

Parent - onPressAdd 函数打开模态框

  constructor(props) {
    super(props);
    this.state = {
        ...
    };
    this.onPressAdd = this.onPressAdd.bind(this);
  }

  ...

  onPressAdd = () => {
    this.refs.addFoodModal.showAddFoodModal();
  }

  <AddFoodModal ref={'addFoodModal'} parentFlatList={this} />

但是,当我尝试将模式链接到另一个父级时,我收到此错误:

Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'getData' of undefined

我只是希望模态在两个父级中调用 getData() 函数,以便它们都接收到各自状态的更新数据。

另一个父级 - 这不会打开模式,但我认为它可以像另一个父级一样将自己作为道具传递下去?

  <AddFoodModal ref={'addFoodModal'} progress={this} />

【问题讨论】:

  • 我找不到任何progress 作为道具传递给您的模态组件,只看到parentFlatList,这就是它说getData 未定义的原因。 progressgetData 的定义在哪里 也许您可以在代码中添加更多详细信息,以便我们提供帮助。
  • 谢谢,你帮助我意识到我实际上并没有将任何东西传递给模态,因为我正试图从另一个组件传递progress。如何让Parent 访问Progress,以便我可以将&lt;AddFoodModal ref={'addFoodModal'} parentFlatList={this} /&gt; 更改为&lt;AddFoodModal ref={'addFoodModal'} parentFlatList={this} progress={progress} /&gt;

标签: javascript reactjs react-native


【解决方案1】:

不确定你从哪里得到progress,如果我理解正确,你可以将progress 作为&lt;Parent progress={progress} /&gt; 之类的道具传递给你的父组件,然后在你的子模态组件中你可以这样做。

同样将this 传递给子组件也不是一个好习惯,您应该只将您实际需要的内容传递给您的子组件,以避免不必要的重新渲染,这会影响性能。在您的代码中,您应该将getData 作为道具传递给子组件,而不是this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2019-07-22
    • 2019-05-08
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多