【问题标题】:Run function from a different class in react native在本机反应中从不同的类运行函数
【发布时间】:2018-09-14 12:04:57
【问题描述】:

我的 react native 应用程序有一个非常简单的问题,我只想在每次单击按钮时执行一个函数,当有单独的类和组件时它变得复杂。

我有 2 个屏幕 DashboardSearch 和 2 个组件 NavbarResults

在仪表板中,我获取一些用户输入并将其存储在 selectedIngredients 变量中 并使用Navbar 组件执行位于同一文件中的函数。

<Navbar handle={() => this.switcher()} />

这个函数是魔法发生的地方(或者可能在 Search.js 屏幕中?)

  switcher() {
    const { navigate } = this.props.navigation;
    navigate('Select', {passedData:this.state.selectedIngredients });
    Alert.alert("send data to Search.js")
  }

选择是Search.js屏幕

一切正常,我使用预期的用户输入selectedIngredients 移动到预期的屏幕,这是Search.js 屏幕的第一次渲染。

 componentDidMount() {
    this.apiCall();
    Alert.alert("did mount search.js")
  }

之后我被卡住了,因为每次我点击我的Navbar 上的 btn 并执行 switcher() 函数时,componentDidMount 不再运行,所以我必须通过点击另一个按钮来刷新页面,这正是我试图避免的事情,因为它对用户体验不利,就像非常糟糕一样。我不想自动更新Results 组件,而只是用一个功能更新它。

下面的代码不是那么重要,它只显示了apiCall 函数和Results 组件的渲染,我不知道我是否应该提供更多信息。请有人帮忙

  apiCall() {
     fetch(url)
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            data: responseJson.results,
         });
     }) 
  }

  componentDidMount() {
    this.apiCall();
    Alert.alert("did mount search.js")
  }

  render() {
    return (
      <View>

      <Navbar title="Results" />
      <Results results={this.state.data} /> 

    </View>
    );
  }
}

我的尝试是在切换器函数中添加this.props.apiCall(),但出现了未定义的错误,就像 hey react native!请将此数据发送到Search.js 屏幕,当您到达时请执行apiCall 函数,它位于那里,而不是这里。

【问题讨论】:

  • componentDidMount 只运行一次!您可以使用 componentWillReceiveProps
  • @gu-mingfeng 非常感谢!它工作得很好,但只有在第二次点击之后!!
  • 同时保留componentDidMount
  • 你在使用 reactnavigation 吗?如果是,您可以使用didFocus 事件reactnavigation.org/docs/en/…
  • @gu-mingfeng with didMount 没有用户输入所以它崩溃:(

标签: javascript reactjs react-native


【解决方案1】:

由于你使用react navigation,在Search.js中你必须绑定didFocus监听器,所以每次屏幕聚焦时都会调用该api

componentDidMount() {
  const { navigation } = this.props;
  navigation.addListener( 'didFocus', () => this.apiCall() );
  this.apiCall();
  Alert.alert("did mount search.js")
}

【讨论】:

  • 我正在使用 this.props.navigation 顺便说一句,我认为存在更好的架构来处理这样的事情。谢谢
猜你喜欢
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2020-10-31
  • 2017-09-20
相关资源
最近更新 更多