How can I do that when the home view navigates to the login view, trigger the useEffect of the login?

前端 未结 2 812
一整个雨季
一整个雨季 2021-01-22 17:04

Basically in login I have a function that verifies if a token exists, and if it exists automatically redirects to thehome view, otherwise it will remai

相关标签:
2条回答
  • 2021-01-22 17:23

    onPress property of Button component is set to a Promise and not a function.

    This will cause a loop back to the Login view whenever Home view is loaded because clearStorage function is being invoked when registering onPress handler.

    The correction to make there is:

     <Button onPress={clearStorage}><Text>Logout</Text></Button>
    

    In addition, the registered effect is skipped on re-render if value of loading doesn't change.

    For your use case, whether the effect runs or not shouldn't be dependent on the value of the loading state.

    Typically, you want to run the effect when the user isn't authorized, i.e when email and token are not set. One can make the assumption that when the component is mounted, both are not set.

    I recommend to set the second argument to useEffect hook to be an empty array. This keeps the effect from being invoked between re-renders. This is akin to side effect implemented in componentDidMount method of a React class.

    
    const Login = props => {
       //...
    
       useEffect(() => {
        getTokenPrevious();
       }, []);
    
    

    You may want to run getTokenPrevious effect every time Login renders as I currently do not see a need for skipping this particular effect.

    I recommend to leave out the second argument set the second argument passed to useEffect to an empty array and always check that a token is there when the component is first mounted.

     useEffect(() => {
        getTokenPrevious();
     });
    

    0 讨论(0)
  • 2021-01-22 17:35

    <Button onPress={clearStorage()} ><Text>Logout</Text></Button>

    clearStorage() call the method, When If loaded. remove the () from clearStorgae.

    <Button onPress={clearStorage} ><Text>Logout</Text></Button>

    0 讨论(0)
提交回复
热议问题