【问题标题】:I upgraded to React-router 6 and my code is broken, what changes would i have to make?我升级到 React-router 6 并且我的代码已损坏,我需要进行哪些更改?
【发布时间】:2022-01-03 11:10:12
【问题描述】:

我正在尝试将其移植到 v6,但是,我似乎没有正确理解语法。此代码在使用 react-router v5 时完美运行。

例如,我知道路由语法发生了变化。

网址.js

import React from "react";
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";

import Login from "./components/Login";
import Home from "./components/Home";

// A wrapper for <Route> that redirects to the login screen if you're not yet authenticated.

function PrivateRoute({ isAuthenticated, children, ...rest}) {
    return (
      <Route
        {...rest}
        render={({ location }) =>
        isAuthenticated ? (
            children
          ) : (
            <Redirect
              to={{
                pathname: "/login/",
                state: { from: location }
              }}
            />
          )
        }
      />
    );
  }

【问题讨论】:

  • react-router 的文档中确实有一个页面记录了从 v5 升级到 v6 需要采取的步骤。在提出问题之前,请至少尝试reactrouter.com/docs/en/v6/upgrading/v5
  • 有什么错误?
  • @Sachihiro 版本 6 中的更改,如果使用版本 5 则没有错误

标签: javascript node.js reactjs react-router react-router-dom


【解决方案1】:

react-router-dom 版本 6 中,自定义 Route 组件已消失,取而代之的是处理呈现内容或重定向逻辑的包装器组件。

替换示例如下:

const PrivateWrapper = ({ isAuthenticated, children }) => {
  const location = useLocation();
  
  return isAuthenticated ? (
    children
  ) : (
    <Navigate to="/login" state={{ from: location }} />
  );
};

用法:

<Routes>
  <Route
    path="...."
    element={(
      <PrivateWrapper isAuthenticated={....}>
        <SomeProtectedComponent />
      </PrivateWrapper>
    )}
  />
</Routes>

为了让PrivateWrapper 更有用一点,它可以渲染一个Outlet 而不是children 属性,用于渲染嵌套的Route 组件。

const PrivateWrapper = ({ isAuthenticated }) => {
  const location = useLocation();
  
  return isAuthenticated ? (
    <Outlet />
  ) : (
    <Navigate to="/login" state={{ from: location }} />
  );
};

用法:

<Routes>
  <Route element={<PrivateWrapper isAuthenticated={...} />} >
    <Route path="...." element={<SomeProtectedComponent />} />
    ..... other protected routes  ......
  </Route>
</Routes>

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2019-07-12
    • 2021-11-20
    • 1970-01-01
    • 2022-01-03
    相关资源
    最近更新 更多