ss_*_*ire 5 flash-message reactjs react-router react-router-v4
这是我要实现的目标:当用户尝试访问我的ReactJS网站上的受保护页面时,我想通过一条简短的消息“请登录”或类似内容将其重定向到首页。我如何使用react-router v4实现此目的。这是我到目前为止的内容:
<Router>
<div>
<Switch>
<Route path="/" component={Home} />
<Route
exact path="/source" render={() => (
isAuthenticated() ? (
<Source />
) : (
<Home /> //I want to Redirect to the Home Page with a flash message if user is not logged in
)
)}
/>
<Route path="/contact" component={ContactUs} />
</Switch>
</div>
</Router>,
);
Run Code Online (Sandbox Code Playgroud)
这对我有用:我使用了react-router v4附带的Redirect方法。它使您能够轻松实现这一目标。
<Route
exact path="/source" render={() => (
isAuthenticated() ? (
<Source />
) : (
<Redirect
to={{
pathname: '/',
state: 'Please sign in'
}}
/>
)
)}
/>
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关重定向的更多信息:React Router v4 - 重定向
| 归档时间: |
|
| 查看次数: |
2335 次 |
| 最近记录: |