【发布时间】:2018-04-24 09:13:21
【问题描述】:
我在我的应用程序中遇到了一个问题,当用户通过身份验证并手动输入他有权访问的所需链接地址时,页面会将他重定向到主页。仅单击链接时不会发生这种情况。
代码如下:
const asyncCheckout = asyncComponent(() => {
return import('./containers/Checkout/Checkout');
});
const asyncOrders = asyncComponent(() => {
return import('./containers/Orders/Orders');
});
const asyncAuth = asyncComponent(() => {
return import('./containers/Auth/Auth');
});
class App extends Component {
componentDidMount() {
this.props.onTryAutoSignup();
}
render() {
let routes = (
<Switch>
<Route path="/auth" component={asyncAuth} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
console.log('Is authenticated: ' + this.props.isAuthenticated);
console.log(routes.props.children);
if (this.props.isAuthenticated) {
routes = (
<Switch>
<Route path="/checkout" component={asyncCheckout} />
<Route path="/orders" component={asyncOrders} />
<Route path="/logout" component={Logout} />
<Route path="/auth" component={asyncAuth} />
<Route path="/" exact component={BurgerBuilder} />
<Redirect to="/" />
</Switch>
);
}
console.log('Is authenticated: ' + this.props.isAuthenticated);
console.log(routes.props.children);
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
}
const mapStateToProps = state => {
return {
isAuthenticated: state.auth.token !== null
};
};
const mapDispatchToProps = dispatch => {
return {
onTryAutoSignup: () => dispatch(actions.authCheckState())
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
以下是手动输入链接时 console.logs 显示的内容:
Is authenticated: false
App.js:38 Array(3)
App.js:55 Is authenticated: false
App.js:56 Array(3)
App.js:37 Is authenticated: true
App.js:38 Array(3)
App.js:55 Is authenticated: true
App.js:56 Array(6)
似乎是这样,因为当手动输入地址时,页面必须重新加载,这就是为什么用户一开始总是未经身份验证的原因。
我尝试弄乱 react-router 给我们的道具,以便以某种方式仍然成功地将用户重定向到正确的页面,但 this.props.match.url 和 this.props.match.path 始终设置为“/”,即使点击在链接上。
所以我的两个问题是:
- 我应该如何处理重定向,当用户手动输入所需地址时,当他通过身份验证(令牌在 localStorage 中设置)?
- 我应该如何解决 react-router 的情况?
【问题讨论】:
标签: javascript reactjs react-router react-redux