我使用react和react-route进行身份验证。 我的目标是:在菜单栏上react-route>登录后重定向到请求的内容
- 登录链接,用户可以通过这个链接
- 登录,如果用户在随后登录我需要在页面的顶部显示不同的菜单结构
- 如果用户刷新然后在浏览器的内容不同 菜单需要呈现,这取决于用户 的状态(登录,或匿名用户)
- 如果一个链接,是不公开的,然后登录匿名用户点击表格需要自动显示 需要
- 成功登录过程后,用户被重定向到所请求的内容
我的解决办法工作正常(如果有人有兴趣的话,我会在这里发布我的代码)。 (5)。我有一个与我最后一个目标有关的问题,(5)。我不知道在图层中发送原始请求的路径信息的最佳做法是什么。最初请求的路径出现在App.js(Route)中。然后它需要传递给onEnter方法。如果它是一个匿名用户,而不是所请求的路径需要传递给显示的Login组件,并且最终在成功登录后需要对原始请求的路由进行重定向。
我的解决方案使用url参数将请求的原始路由信息传递给登录组件。
这里是我的代码:
App.js
function requireAuth(nextState, replace) {
if (!auth.loggedIn())
replace({
pathname: '/login?route=' + nextState.location.pathname,
state: { nextPathname: nextState.location.pathname }
})
}
ReactDom.render(
<Router history={hashHistory} onUpdate={() => window.scrollTo(0, 0)}>
<Route path="/" component={MainLayout}>
<IndexRoute component={Home} />
<Route path="login" component={Login} />
<Route path="login?route=:route" component={Login} />
<Route path="logout" component={Logout} />
<Route path="about" component={About} />
<Route path="profile" component={Profile} onEnter={requireAuth} />
</Route>
</Router>,
document.getElementById('root')
);
Login.js
import React from 'react';
import { withRouter } from 'react-router';
import auth from '../auth/Auth';
import Button from "react-bootstrap/lib/Button";
export default class Login extends React.Component {
doRedirect() {
if (this.props.location.query.route)
this.props.router.push(this.props.location.query.route);
else
this.props.router.push('/');
}
render() {
return (
<div style={style.text}>
<h3>LOGIN FORM</h3>
<Button bsStyle="primary" onClick={() => auth.login("username", "password", this.doRedirect.bind(this))}>
Login
</Button>
</div>
);
}
}
// wrap with the withRouter HoC to inject router to the props, instead of using context
export default withRouter(Login);
有没有更好或更符合反应液通过请求的URI来登录组件?
THX。
只有一个改善我能做些什么:更换({ 路径: '/登录', 查询:{路线:nextState。location.pathname}, state:{nextPathname:nextState.location.pathname} }) – zappee