首页 > 解决方案 > 添加两个 HOC 组件不行

问题描述

我尝试将 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 };

和开关部分:

    <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:3000/switch-role,子页面可以正确显示,但是如果我输入/localhost:3000/user-list,我会看到一个黑页。如果我删除 AuthWithoutLayout 部分,将显示用户列表页面。

请帮忙。

标签: reactjsswitch-statement

解决方案


上面代码的问题是 Switch 渲染了 First match 组件。因此,当您在AuthWithoutLayout没有 Route 的情况下进行渲染时,它假定这是需要渲染的组件并且不会进一步检查,因此Auth会被忽略

解决方案是使用 Routes 编写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>

推荐阅读