我已经将用户是否通过身份验证存储在 redux 中。我想要做的是,一旦我转到 localhost:3000/
我希望它在用户未通过身份验证时显示主页,或者在用户通过身份验证时显示仪表板。这是我目前所拥有的。
export default (
<Route path="/" component={App} >
<IndexRoute component={HomePage} />
<Route path="/dashboard" component={Dashboard} />
<Route path="*" component={NotFound} />
</Route>
);
我希望 IndexRoute
以身份验证为条件。
最佳答案
在 HomePage
组件中,您可以根据身份验证呈现另外两个组件。例如
class HomePage extends Component {
//...
render() {
if (currentUser) return <Dashboard /> // if user exists in the store
else if (fetchingCurrentUser) return <LoadingView /> // if you need to fetch the user show a loading page
else return <UnauthenticatedHomeView /> // else, return a homepage for unauthenticated users
}
}
通过这种方式,您可以完全消除 '/dashboard'
路线,这样用户就不必前往该路线即可到达他们的仪表板。此外,HomePage
只是充当它可以在其中呈现的不同可能组件的容器。
您的路线将如下所示。
export default (
<Route path="/" component={App} >
<IndexRoute component={HomePage} />
<Route path="*" component={NotFound} />
</Route>
);
另一个注意事项:您还可以将 onEnter
函数连接到路由,以便在即将进入路由时运行。在这里你可以做一些其他的认证来保护路由。但是,如果您使用 onEnter
,则上面的示例实现将不得不更改,但您现在知道您有那个选项。
关于javascript - React-Router:如果未通过身份验证则显示主页,如果在 "/"中通过身份验证则显示仪表板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680920/