在不起作用中添加<Switch/>两个 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/将角色切换到浏览器,子页面可以正确显示,但如果我输入localhost:3000/user-list,我会看到一个黑色页面。如果删除AuthWithoutLayout部分,则会显示用户列表页面。

请帮忙。

切换

呈现与位置匹配的第一个子<Route><Redirect>

BTW,它们都不是高阶组件,而是简单的包装器组件。您可以更正Auth组件,但AuthWithoutLayout是一个布局容器,更适合装饰除路由或重定向之外的任何内容。

基本上,在您的"auth"组件中,您希望检查一些身份验证条件,如果经过身份验证,则呈现Route,否则您将用户重定向到您想要的位置,通常是登录路径。

您的容器还应该应用单一责任原则,这意味着身份验证容器应该只关心身份验证,布局容器应该只关注内容布局。

下面是一个示例身份验证路由重写

// 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>

上面代码的问题是Switch渲染了First match组件。因此,当您在没有Route的情况下渲染AuthWithoutLayout时,它假设这是需要渲染的组件,并且不会进一步检查,因此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>

最新更新