【问题标题】:How to set up routes and redirect in React如何在 React 中设置路由和重定向
【发布时间】:2021-10-26 09:45:04
【问题描述】:

我正在使用 React 构建一个应用程序并使用 react-router-dom。

我当前的设置在大多数情况下都有效,但如果路线未知并且我认为我没有使用最佳做法,则无法渲染。

这就是我所拥有的:

index.js

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <Suspense fallback={<div>Loading...</div>}>
                <Route path="/" component={Main} />
            </Suspense>
        </BrowserRouter>
    </Provider>,
  document.getElementById('root')
);

然后在我的 Main.js 类组件中,如果用户未通过身份验证,我会渲染登录页面和this.props.history.push('/login')。如果用户通过身份验证,我有以下路线:

{this.props.location.pathname === '/' || this.props.location.pathname.endsWith('dashboard') && <Dashboard />}
<Switch>
    {
        userAdmin &&
        <React.Fragment>
            <Route exact path="/users" component={Users} />
            <Route path="/users/:id" component={User} />
        </React.Fragment>
    }
    {
        productAdmin &&
        <React.Fragment>
            <Route exact path="/products" component={Products} />
            <Route path="/products/:id" component={Product} />
        </React.Fragment>
    }
    <Route component={Dashboard} />
</Switch>

如果路由不匹配,我想将经过身份验证的用户重定向到/ 并呈现Dashboard

我添加了&lt;Route component={Dashboard} /&gt;,它不起作用。 我也试过&lt;Redirect to="/dashboard" /&gt;,但它什么也没做。 我尝试删除开关,然后它似乎按预期工作,但每当我尝试直接访问任何其他现有路由时它也会重定向。

我应该如何正确设置?

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    对于需要认证的路由,你可以创建一个抽象的PrivateRoute,接受一些permissionsrouteComponent作为props。它将检查用户是否具有这些权限并将重定向到route,否则它将重定向到默认页面。 参考:Creating Private Routes

    对于所有人都可以访问的页面,您可以使用react-routerRoute 组件。

    您可以通过以下方式设置Routes 组件:

    ...
    <Switch>
       <PrivateRoute permission={userAdmin} route="/users" component={Users} /> 
       <PrivateRoute permission={productAdmin} route="/products" component={Products} />
       <Route path="/" component={Dashboard} />
    //some more routes
    </Switch>
    

    你的index.js 只需要渲染Routes 组件

     ReactDOM.render(
        <Provider store={store}>
            <BrowserRouter>
                <Suspense fallback={<div>Loading...</div>}>
                    <Routes />
                </Suspense>
            </BrowserRouter>
        </Provider>,
      document.getElementById('root')
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 2019-08-23
      • 2016-12-20
      • 1970-01-01
      相关资源
      最近更新 更多