简体   繁体   English

React Router Docs & Redirect vs history.push()

[英]React Router Docs & Redirect vs history.push()

I've tried to read previous answers but unfortunately they only created more questions.我试图阅读以前的答案,但不幸的是他们只提出了更多问题。 In react router docs https://reactrouter.com/web/example/auth-workflow on line 124 after signout they use history.push("/")在注销后第 124 行的反应路由器文档https://reactrouter.com/web/example/auth-workflow中,他们使用 history.push("/")

What's the purpose of history.push() here and why not use Redirect instead? history.push() 这里的目的是什么,为什么不使用 Redirect 呢?

Redirect is more of a component which you render in case some logic exists or does not exists, consider following example, it is generally used when you have some logic on route and want to do conditional redirection. Redirect更多的是在某些逻辑存在或不存在的情况下呈现的组件,请考虑以下示例,它通常用于当您在路由上有一些逻辑并想要进行条件重定向时。

Similarly, you use history.push when you have some event triggered action, like you click on a button, which in turn does some validation and then might re-direct you based on your business logic.类似地,当您有一些事件触发操作时,您使用history.push ,例如您单击一个按钮,这反过来会进行一些验证,然后可能会根据您的业务逻辑重定向您。

I have given examples for both the cases, hope it helps.我已经给出了这两种情况的例子,希望它有所帮助。

const Admin = () => {
  const [isInvalidUser, setUserInvalid] = useState(false);  
  
  useEffect(() => {
    // check if valid user via API call
    setUserInvalid(true);
  }, [])
  
  // here you are returning a component in form of Redirect
  // this is automatically executed when you open a particular route, it is not event triggered
  if(isInvalidUser) {
    return <Redirect to="/auth" />;
  }

  return <AdminView />;
}

const Login = () => {
  
  const handleLogin = () => {
   
    // business logic to validate login
    if(validUser) {
      // you cannot have return statement here with Redirect as this is a handler
      history.push("/home");
    }
  
  }
  
  // assume you have state for username and password
  return (
    <button onClick={handleLogin}>Submit</button>
  );

}

You can use whichever you need based on your use case and approach.您可以根据您的用例和方法使用任何您需要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM