使用 React Router <Redirect /> 不会重定向到任何地方,但为什么呢?

IT技术 javascript reactjs redirect react-router jsx
2021-05-04 11:41:45

在 .then() 内完成注册后,我一直试图将用户重定向回“/”或“/home”,但除重定向外,promise 中的所有内容都执行失败。我只使用 if(true) 来测试它,它确实到了那个点,因为我可以让 console.log 在那里显示文本,但只是重定向是徒劳的..

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

}
2个回答

Redirect需要渲染才能工作!您可以尝试使用history.push代替。

你实际做的是返回一个react组件。如果我没有错的话,你想要实现的是向他发送“/home”,在这种情况下,如果它是一个Router 组件的直接子级,如果它不是 Router 组件的直接子级,则在使用函数组件时必须使用钩子,如果使用类组件则必须使用 HOC。功能组件示例。

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)