简体   繁体   中英

Run function from a different class in react native

I have a very simple issue with my react native application, I just want to execute a function everytime a button is clicked, it become complicated when there's separate classes and components.

I have 2 screens Dashboard and Search and 2 components Navbar and Results

In Dashboard I grab some user input and store it in selectedIngredients variable and with the Navbar component I execute a function located in the same file.

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

This function is where should the magic happens (or maybe in Search.js screen?)

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

Select is Search.js screen

Everything workin fine and I move to the expected screen with the expected user input selectedIngredients , this is the first render of Search.js screen.

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

After that I'm stuck because everytime I click on the btn on my Navbar and execute the switcher() function, componentDidMount do not run anymore so I have to refresh the page by clicking on another button, this is exactly what I'm trying to avoid because it's bad for UX, like really bad. I am not looking to update Results component automatically but just update it with one function.

The code below is not that important it only shows apiCall function and render of Results component, I don't know if I should put more information. Please someone help

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

My attempt was to add this.props.apiCall() in switcher function but got undefined error, something like hey react native! please send this data to Search.js screen and when you arrive please execute apiCall function, it's located there, not here.

Since you are using react navigation , in Search.js you have to bind didFocus listener, so the api will be called every time your screen is focused

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

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