当包裹在另一个组件中时,React Router 不呈现传递给路由的组件

React Router not rendering component passed to route when wrapped in another component

我在我的应用程序中使用 typescript、React 和 ReactRouter。

我想实现一个 AdminRoute 组件,该组件仅在用户具有特定授权级别时呈现,否则执行重定向(或显示 "access denied" 消息)。如果我直接在我的 App 组件中实现逻辑,一切正常。

但是如果我创建 AdminRoute 组件并在 App 中使用它,它首先根本不会呈现(当使用 Link 元素重定向时)。 但是刷新页面后,不管当前路由的组​​件下面是什么URL,总是渲染。

我的代码:

应用组件:

const App: React.SFC<{}>  = (
  <div>
    <BrowserRouter>
       <>
         <Route render={props => <Header {...props} />} />
         <Route exact path="/" component={Main} />{' '}
         <Route exact path="/login" render={prop=>this.loginRedirect(props)}/>
         <Route exact path="/register" render={props => <Register {...props} />} />
         <Route exact path="/user" component={UserCard} />


         <AdminRoute exact path="/adminSettings" component={RestrictedSettings} />

         {/*<Route 
              exact path="/adminSettings" 
              render={props => store.user && 
                store.isAuthorized(UserRoles.Admin) 
                  ? <RestrictedSettings /> 
                  : <h2>Access denied</h2>
              }
            />
         */}

      </>
    </BrowserRouter>
  </div>
);

注释掉的代码有效,但 AdminRoute 无效。

AdminRoute 看起来像这样:

const AdminRoute: React.SFC<RouteProps> = 
  ({ component: Component, ...other }) => {
    console.log('accessing protected route');

    return (
      <Route
        {...other}
        render={props =>
          store.user && store.isAuthorized(accessLevel) 
            ? <Component {...props} /> 
            : <h2>Access denied</h2>
        }
      />
    );
});

我希望内联实现和功能组件的工作方式完全相同。

有什么区别?我忘记传递 属性 了吗?打字稿编译有问题吗?

请帮忙。

我想问题是路由器渲染了所有匹配的路由,而不是只渲染了一个。您应该尝试使用 Switch 组件,以便它只呈现第一个匹配的组件:

import {Switch} from "react-router-dom"

const App: React.SFC<{}>  = (
  <div>
    <BrowserRouter>
       <Switch>
         <Route render={props => <Header {...props} />} />
         <Route exact path="/" component={Main} />{' '}
         <Route exact path="/login" render={prop=>this.loginRedirect(props)}/>
         <Route exact path="/register" render={props => <Register {...props} />} />
         <Route exact path="/user" component={UserCard} />


         <AdminRoute exact path="/adminSettings" component={RestrictedSettings} />

         {/*<Route 
              exact path="/adminSettings" 
              render={props => store.user && 
                store.isAuthorized(UserRoles.Admin) 
                  ? <RestrictedSettings /> 
                  : <h2>Access denied</h2>
              }
            />
         */}

      </Switch>
    </BrowserRouter>
  </div>
);

在此处阅读更多内容:https://reacttraining.com/react-router/web/guides/basic-components