【问题标题】:BrowserRouter - how to access history? Change location in component or in action?BrowserRouter - 如何访问历史记录?更改组件或操作中的位置?
【发布时间】: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 组件中的constructorsuper 方法。

class Login extends Component {
    constructor(props, context) {
        super(props, context);

现在,我的问题是。进行位置更改的最佳地点是什么?组件本身,还是在动作中(thunk)?我提到 thunk 是有目的的,因为我将更改代码并对后端进行一些异步调用。使用`BrowserRouter时,如何在绑定到它的组件和动作中访问history对象?

【问题讨论】:

标签: reactjs react-router-v4 browser-history


【解决方案1】:

我的建议是:在 componentDidMount 生命周期挂钩中更改位置。

你有一些props 来比较,做一些动作等等......

https://reactjs.org/docs/react-component.html#componentdidmount.

创建 HOC 来管理位置变化会更好

更新

首先,NO更改render func中的位置,这会产生错误。

根据您的应用程序结构,有很多soloutin... 另一种解决方案是使用'componentWillReceiveProps'

componentWillReceiveProps(nextProps, nextState){
  if(nextProps.isLoggedIn===true&&this.props.isLoggedIn===false){
    nextProps.history.push('path_for_logged_in')
  }
}

对于 props 中的访问历史记录,您需要使用 withRouter HOC 包装您的组件

import { withRouter } from 'react-router'


withRouter(YourComponent)

【讨论】:

  • 无法更改componentDidMount 中的位置,因为在登录时正确的凭据后应立即更改位置,换句话说,在调度successful login 操作后。所以它应该在动作(thunk)或组件的登录功能中,点击时调用。所以生命周期钩子不是解决方案。
猜你喜欢
  • 2022-10-15
  • 1970-01-01
  • 2021-09-02
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
相关资源
最近更新 更多