在<Switch>中添加两个HOC组件,无法工作。

问题描述 投票:0回答:1

我想把2个HOC放在交换机上,但只有第一个路由器被调用,第二个没有被调用。

 // if user is not login, show login page, otherwise add a side bar to children and show up    
    @inject("userStore")
    @observer
    class Auth extends React.Component {
      render() {
        let { userStore, children } = this.props;
        return userStore.isLogin ? <CoreLayout>{children}</CoreLayout> : <Login />;
      }
    }

    // if user is not login, show login page, otherwise show children
    @inject("userStore")
    @observer
    class AuthWithoutLayout extends React.Component {
      render() {
        let { userStore, children } = this.props;
        return userStore.isLogin ? children : <Login />;
      }
    }
    export { Auth, AuthWithoutLayout };

还有Switch部分,我在浏览器上输入localhost:3000switch-role,子页面可以正常显示,但如果我在浏览器上输入localhost:3000switch-role,子页面可以正常显示。

    <ConfigProvider locale={locale}>
        <Switch>
          <Route exact path="/" component={Login} />
          <AuthWithoutLayout>
             <Route path="/switch-role" component={SwitchRole} />
          </AuthWithoutLayout> 
          <Auth>
              <Route path="/user-list" component={UserList} />
          </Auth>
        </Switch>
   </ConfigProvider>

在浏览器中输入localhost:3000switch-role,子页面可以正常显示,但输入localhost:3000user-list,就会出现黑色页面,如果去掉AuthWithLayout部分,就会出现user-list页面。

请帮助我。

reactjs switch-statement
1个回答
1
投票

交换机

抚养第一个孩子 <Route><Redirect> 匹配的位置。

另外,这些都不是高阶组件,而是简单的封装组件。你可以纠正你的 Auth 组成部分,但你的 AuthWithoutLayout 是一个布局容器,更适合用来装饰路由或重定向以外的任何东西。

基本上,在你的 "Auth "组件中,你想检查的是 一些 认证条件,如果通过认证,则呈现 Route否则,你就把用户重定向到你想要的地方,通常是登录路径。

你的容器也应该应用单一责任原则,也就是说,一个 auth 容器应该只关注认证,一个布局容器应该只关注内容布局。

下面是一个重写Auth路由的例子

// if user is logged in, render Route, otherwise Redirect to login "/"
@inject("userStore")
@observer
class AuthRoute extends Component {
  render() {
    const { userStore, ...props } = this.props;
    return userStore.isLogin ? <Route {...props} : <Redirect to="/" />;
  }
}

用法。

<ConfigProvider locale={locale}>
  <Switch>
    <Route exact path="/" component={Login} />
    <AuthRoute path="/switch-role" component={SwitchRole} />
    <AuthRoute path="/user-list" component={UserList} /> // <-- use a layout container to decorate UserList!
  </Switch>
</ConfigProvider>

1
投票

上述代码的问题是Switch渲染的是First match组件。所以当你渲染 AuthWithoutLayout 没有Route,它就会认为这是需要渲染的组件,而不会进一步检查,因此也就是 Auth 被忽略

解决办法是写 AuthWithoutLayoutAuth 两者都有路由

<ConfigProvider locale={locale}>
        <Switch>
          <Route exact path="/" component={Login} />
          <Route path="/switch-role">
              <AuthWithoutLayout>
                   <SwitchRole />
              </AuthWithoutLayout> 
          </Route>
          <Route path="/user-list">
              <Auth>
                   <UserList />
              </Auth> 
          </Route>
        </Switch>
   </ConfigProvider>
© www.soinside.com 2019 - 2024. All rights reserved.