How to change a state of a Component in React navigation

Asked

Viewed 295 times

1

I need to change a state within a function of React navigation, this state will change a behavior in the Component

function TabOneNavigator({navigation}) { 
    React.useEffect(() => {
    const unsubscribe = navigation.addListener('tabPress', e => {

      if(global.webview.startUrl != global.webview.props.source.uri){
        //aqui eu preciso chamar o metodo resetWebViewToInitialUrl()
        //que está no componente
      }
    });

    return unsubscribe;
  }, [navigation]);

  return (
    <TabOneStack.Navigator>
      <TabOneStack.Screen
        name="Perfil"
        component={TabOneScreen}
        options={{ headerTitle: 'IzyJob' }}
      />
    </TabOneStack.Navigator>
  );
}

i am trying to change the state of the component when the React Navigator button is clicked, that is the code of my component

export default class App extends React.Component {

  this.state = {
    key: 1,
    url: 'https://www.google.com'
  };
  
  resetWebViewToInitialUrl = () => {
    this.setState({
      key: this.state.key + 1
    });
  };

  render() {
    return <WebView 
    key={ this.state.key }
    ref={(ref) => { global.webview = ref; }}
    source={{ uri: this.state.url }} 
    onNavigationStateChange={this._onNavigationStateChange.bind(this)}
    style={{ marginTop: 0 }} />;
  }
} 

I have tried using props but not enough in the function of Navigator, also tried creating a global but then I can not change the state

1 answer

0

When using the and need to handle related operations should use in your documentation the guide Navigation Events, at these events can be written update solutions as you are asking in your question.

In the documentation has 4 events:

  • phocus - This event is issued when the screen enters
  • Focus Blur - This event is issued when the screen is blurred
  • beforeRemove - This event is issued when the user is leaving the screen, there is a chance to prevent the user from leaving
  • state (Advanced) - This event is issued when the browser state changes

and there are already Hooks as an example of the documentation itself:

import { useFocusEffect } from '@react-navigation/native';

function Profile({ userId }) {
  const [user, setUser] = React.useState(null);

  useFocusEffect(
    React.useCallback(() => {
      const unsubscribe = API.subscribe(userId, user => setUser(data));

      return () => unsubscribe();
    }, [userId])
  );

  return <ProfileContent user={user} />;
}

Code taken from link: Triggering an action with the useFocusEffect hook


In your code I could notice that the event is in one component and is called in another component, I believe you have to use either Redux or Context to make this available globally in your code and with the events explained above using the focus may contemplate your doubt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.