Using React Router the <Redirect /> Does not redirect anywhere, but why?

北城余情 提交于 2021-01-28 20:23:23

问题


I have been trying to Unsuccesfully redirect a user back ho "/" or "/home" after registration is done inside .then() , eveyrthing inside promise executes EXCEPT the redirection. I used just if(true) to test it, and It does go to that point, because I can get the console.log to display text there, but just Redirect is fruitless..

const createUserWithEmailAndPasswordHandler =(event) => { event.preventDefault();

    auth.createUserWithEmailAndPassword(signUp.email, signUp.pw1).then((authData) =>{
        console.log("authData" + authData);
        addUserDataToDb({
            email: signUp.email,
            username: signUp.username,
        });
        if (true) {
            return <Redirect to='/home' />;
        }
    })
        .catch((error) => {
            setSignUp({
                ...signUp,
                error: error,
            });
            console.error(error);
        });

    setSignUp(INITIAL_STATE);

}

回答1:


Redirect need to be rendered in order to work! You can try using history.push instead.




回答2:


What you actually doing is you return a react Component. And if I'm not wrong what you're trying to achieve is to send him '/home' and in that case you're going to need to use the history object that the Router component provides to your component via props if it's a direct child of the Router component, if it's not a direct child of the Router component you'll have to use hooks if you're using function components or HOC if you're using Class components. Example for function component.

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}


Example for Class component.

  import { withRouter } from "react-router";
  class MyComponent extends React.Component {
onClickHandler(){
this.props.history.push('/home')
}
   render() {
     return <button onClick={onClickHandler}>Hello</button>;
   }
}
export default withRouter(MyComponent)


来源:https://stackoverflow.com/questions/64371190/using-react-router-the-redirect-does-not-redirect-anywhere-but-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!