簡體   English   中英

如何在反應 v6 中重定向

[英]how to redirect in react v6

登錄后,我需要導航回原始請求的 URL。

例如,用戶輸入www.eCart.com/Cart ,因為用戶未通過身份驗證,它將導航到登錄頁面www.eCart.com/login

一旦通過身份驗證,它應該會自動導航回www.eCart.com/Cart

我的 protectedRoute.js 看起來像這樣

 import React from 'react' import { connect } from 'react-redux' import { Navigate, Outlet, useLocation, useNavigate} from 'react-router-dom' export const withRouter = (Component) => { //works only for react16-17 //hooks const Wrapper = (props) => { const location = useLocation() const navigate = useNavigate(); return ( <Component navigate = {navigate} {...props} location={location} {...props} /> ); }; return Wrapper; }; const ProtectedRoute = ({component:Component, auth,...rest}) => ( auth.isAuthenticated? <Outlet />: <Navigate to={`/login/${rest.location.search}`} replace /> ) const mapStateToProps = (state) => ({ auth: state.auth }) export default connect(mapStateToProps)(withRouter(ProtectedRoute))

我的 app.js 是這樣的

 function App(props) { useEffect(() => { store.dispatch(setCurrentUser()) }, []) const grabProductsFromStorage = () =>{ const userId = decodeUser().user.id const cartProducts = JSON.parse(localStorage.getItem("products")) const context = {products: cartProducts, userId} store.dispatch(addToCart(context)) localStorage.removeItem("products") } if(localStorage.getItem("token") && localStorage.getItem("products")){ grabProductsFromStorage() } return ( <Provider store={store}> <Router> <Routes> <Route exact path="/" element={<Landing/>} /> <Route exact path="/products/:id" element={<ProductDetails/>} /> <Route exact path="/" element={<ProtectedRoute/>}> <Route exact path="/dashboard/*" element={<Dashboard {...props} nestedRoute={Home} />} /> <Route exact path="/cart" element={<Cart />} /> </Route> <Route exact path="/register" element={<Register/>} /> <Route exact path="/login" element={<Login/>} /> </Routes> </Router> </Provider> ); }

另外,我在某處看到使用 state 在導航中使用它的位置,但是當我這樣做時,它會拋出 Unexpected use of 'location' 的錯誤

您需要先存儲該購物車路線。 如果用戶未經過身份驗證並重定向到登錄頁面,則從購物車重定向到登錄頁面時,您需要將購物車路由存儲在本地存儲中或 state 中的某個位置,因此登錄后您可以檢查我們是否有登錄后路由,然后您可以重定向用戶訪問該頁面。

有一些方法:

將用戶重定向到另一個頁面:

 function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home')
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

重定向到上一頁

function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(-1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

將用戶重定向到下一頁

function Redirect() {
  let navigate = useNavigate();
  function handleClick() {
    navigate(1)
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM