React-Router:如果未通过身份验证则显示主页,如果在“/”中通过身份验证则显示仪表板
React-Router: Display homepage if not authenticated or dashboard if authenticated in at "/"
如果用户通过身份验证,我已经存储在 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
,上面的示例实现将不得不更改,但您现在知道您有那个选项。
您可以在 JSX 中使用 conditional rendering。
export default (
<Route path="/" component={App} >
{isLoggedIn ? (
<IndexRoute component={HomePage} />
) : (
<IndexRoute component={Dashboard} />
)}
</Route>
);
如果用户通过身份验证,我已经存储在 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
,上面的示例实现将不得不更改,但您现在知道您有那个选项。
您可以在 JSX 中使用 conditional rendering。
export default (
<Route path="/" component={App} >
{isLoggedIn ? (
<IndexRoute component={HomePage} />
) : (
<IndexRoute component={Dashboard} />
)}
</Route>
);