我有一个带有登录功能的应用程序和带有线程的仪表板。特定线程有它自己的 url 地址。如果我想与某人共享线程 url,他需要先登录,然后我需要将他重定向回线程的 url。所以基本上我需要以某种方式在他进入应用程序后立即获取位置,并将其保存到例如。 redux store,成功登录后,将他重定向回线程 url。除了获取传入网址之外,我一切正常。
现在我有了这个routes.js:
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { userAuth: { loggedIn }} = store.getState();
if (!loggedIn) {
replace('/login');
}
cb();
}
checkAuth()
}
<Route path="/" component={App}>
<IndexRedirect to="/dashboard" />
<Route path="/login" component={LoginPage} />
<Route onEnter={requireLogin}>
<Route path="/dashboard" component={Dashboard} />
<Route path="/thread/:id" component={SingleThread} />
</Route>
</Route>
我的应用程序 react 组件我有:
class App extends Component {
constructor(props) {
super(props)
}
getChildContext() {
console.log("LOCATION:" + JSON.stringify(this.props.location))
return { location: this.props.location }
}
...
render() {
const { children } = this.props
return (
<div className={style.normal}>
{children}
</div>
)
}
}
获取传入线程的 url,但每次我输入例如。/thread/3 控制台记录“/”或“/login”,我将其重定向到未登录的用户。也许 React Router TransitionHooks 可以帮助我,但我不知道在这种情况下如何正确使用它。
我正在使用react-router v2.0.0和react-router-redux v4.0.2
感谢您的建议!
最佳答案
您可以尝试将私有(private)区域包装在组件中,例如 ->
<Route path="/" component={App}>
<IndexRedirect to="/dashboard" />
<Route path="/login" component={LoginPage} />
<Route component={PrivateWrapper}>
<Route path="/dashboard" component={Dashboard} />
<Route path="/thread/:id" component={SingleThread} />
</Route>
</Route>
您的 PrivateWrapper 应该如下所示
class PrivateWrapper extends React.Component {
constructor(props) {
super(props);
this.checkIfUserIsValid = this.checkIfUserIsValid.bind(this);
}
checkIfUserIsValid(){
let {user} = this.props.auth;
if(user == null){
this.context.router.push("/login");
}
}
render(){
let {user} = this.props.auth;
if(user == null)
return <div></div>
else{
return <div>{this.props.children}</div>
}
}
PrivateWrapper.contextTypes = {
router: React.PropTypes.object
};
export default connect(**Auth state here**)(PrivateWrapper);
这样你甚至不需要钩子(Hook)或任何东西。
关于javascript - 捕获传入路由并在登录后重定向回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36794081/