【发布时间】:2018-12-31 18:15:21
【问题描述】:
我在我的React/Redux 应用程序中使用BrowserRouter,因此我不会创建history 对象,也不会将其传递给BrowserRouter,因为它会处理自己的历史记录。目前,我模拟了登录功能,这是Login 组件中的函数(在authActions 中调用login thunk):
handleSubmit = (e) => {
e.preventDefault();
this.props.authActions.login({
email: this.state.email,
password: this.state.password
});
};
AuthActions 映射到组件道具:
function mapDispatchToProps(dispatch) {
return {
authActions: bindActionCreators(authActions, dispatch)
}
}
这是login thunk in authActions:
export function login(userData) {
return function (dispatch) {
if(userData.email === 'test@test.com' && userData.password === 'pw'){
sessionStorage.setLoggedUser(JSON.stringify(userData));
dispatch(loginSuccess(userData));
this.context.router.history.push('/');
} else {
dispatch(loginFail());
}
}
}
我收到 context 未定义的错误,但成功登录后,应用程序导航到“/”路由。我将context 作为第二个参数传递给Login 组件中的constructor 和super 方法。
class Login extends Component {
constructor(props, context) {
super(props, context);
现在,我的问题是。进行位置更改的最佳地点是什么?组件本身,还是在动作中(thunk)?我提到 thunk 是有目的的,因为我将更改代码并对后端进行一些异步调用。使用`BrowserRouter时,如何在绑定到它的组件和动作中访问history对象?
【问题讨论】:
-
使用 react-router-dom 中的 withRouter。例如:stackoverflow.com/questions/51477910/…
-
为了在actions中访问history,你要么需要在dispatch action时从组件中传递它,要么你可以创建一个history对象,详情请参考stackoverflow.com/questions/48514773/…
-
react-router-v4 也不支持从上下文访问路由器,你可以看看这个答案stackoverflow.com/questions/44127739/…
标签: reactjs react-router-v4 browser-history