在 React Native 中运行来自不同类的函数

IT技术 javascript reactjs react-native
2021-05-10 16:22:36

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

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

在 Dashboard 中,我获取一些用户输入并将其存储在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")
  }

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

下面的代码不是那么重要,它只显示apiCallResults组件的功能和渲染,我不知道是否应该添加更多信息。请有人帮忙

  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功能,它位于那里,而不是这里。

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