简体   繁体   English

在 React Router Dom v6 中重定向

[英]Redirect in React Router Dom v6

I need help after the update from React Router Dom to version 6. I have a code snippet for redirects after a user logged in which should work in version 5, but I think "Redirect" is depreceated.从 React Router Dom 更新到版本 6 后,我需要帮助。我有一个用于在用户登录后重定向的代码片段,它应该在版本 5 中工作,但我认为“重定向”已被弃用。 Now, I am looking for some replacement which integrates into my former code.现在,我正在寻找一些集成到我以前的代码中的替代品。

Here is my code example which should work in React Router Dom version 5:这是我的代码示例,它应该在 React Router Dom 版本 5 中工作:

<Route path='/signin' render={() => this.props.currentUser? (<Redirect to =''/>): (<SignIn/>)}></Route>

I think I should use something like "Navigate", but I am not sure how to implement this with the conditional statement since for version 6 I also would have to add the "element={}" part.我想我应该使用类似“Navigate”的东西,但我不确定如何使用条件语句来实现它,因为对于版本 6,我还必须添加“element={}”部分。

Let me know in case you need more information.如果您需要更多信息,请告诉我。

Thanks!谢谢!

The new pattern for handling "authentication" or essentially conditional routing/redirecting is to use a wrapper component to handle the conditional logic and return the child or the Navigate .处理“身份验证”或本质上是条件路由/重定向的新模式是使用包装器组件来处理条件逻辑并返回子节点或Navigate

const SignInWrapper = ({ children, currentUser }) => {
  return currentUser ? <Navigate to="/" replace /> : children;
};

... ...

<Route
  path='/signin'
  element={<SignInWrapper currentUser={this.props.currentUser}>
    <SignIn />
  </SignInWrapper>}
/>

I want to redirect user to the page, from which he was redirected.我想将用户重定向到他被重定向的页面。 How can i do that using this code in V6?我如何在 V6 中使用此代码来做到这一点?

const PrivateRoute = ({ children, ...rest }) => { 


let {user} = useAuth();
  return (
   user.displayName ? (children):(<Navigate to='/login' />)
  )
}

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

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