访问动作创建者中的历史对象



我有许多动作创建者,其中,如果从服务器回来的响应是401,我想注销用户(一个需要访问历史记录对象的共享功能(。我需要在动作创建者内有访问历史对象。我应该怎么做?

这是动作创造者:

export function fetchGroups() {
  return (dispatch) => {
    axios.get(GROUP_ENDPOINT, AUTHORIZATION_HEADER)
      .then(response => {
          dispatch(groupsFetchSucceeded(response.data));
      })
      .catch(({response}) => {
        if (response.status ===  401) { // Unauthorized
          //logout user &
          //this.props.history.push('/login'); HERE I NEED ACCESS TO HISTORY
        } else {
          dispatch(groupsFetchErrored({
            error: response.data.message
          }));
        }
      })
  };
}

这是我的app.js代码:

ReactDOM.render(
  <Provider store={store}>
      <BrowserRouter>
        <div>
          <Switch>
            <Route exact path="/login" render={props =>
                isAuthenticated() ? <Redirect to='/' /> :
                <LoginForm {...props}/>
            } />
            <Route exact path="/register" render={props =>
                isAuthenticated() ? <Redirect to='/' /> :
                <RegisterForm {...props}/>
            } />
            <PrivateRoute exact path="/group" component={GroupList}/>
            <PrivateRoute exact path="/group/new" component={GroupList} componentProps={{
              modal:{
                'content': NewGroup,
                'className': 'new-group-modal'
              }}}
            />
            <PrivateRoute exact path="/group/:id" component={ShowGroup} />
            <PrivateRoute component={Home}/>
          </Switch>
        </div>
      </BrowserRouter>
  </Provider>
  , document.querySelector('.container')); 

这是组件代码:

class GroupList extends Component {
  _onDelete = (groupId) => {
    this.props.deleteGroup(groupId);
  }
  render() {
    const { groups } = this.props;
    let configs = [
      {
        name: 'name',
        label: 'Group'
      }
    ];
    let actions = [{
      action: this._onDelete
    }];
    return (
      <div>
        {
          <DataTable className="group-table" data={_.map(groups, group => group.data)} configs={configs} actions={actions}/>
        }
      </div>
    );
  }
}
function mapStateToProps(state) {
  return { groups: state.groups.data};
}
const mapDispatchToProps = (dispatch) => {
    return {
        deleteGroup: (id) => dispatch(deleteGroup(id))
    };
};
export default connect(mapStateToProps, mapDispatchToProps)(GroupList);

制作history.js文件

import createHistory from 'history/createHashHistory'
export default createHistory()

在您的action.js文件中

import history from './history'
history.push('/abc')

来源:github https://github.com/reaecttraining/reaect-router/issues/3498

//this.props.history.push('/login'); // HERE I NEED ACCESS TO HISTORY

将道具传递给fetchgroups:

export function fetchGroups(props) {
    // ...
}

尝试:

props.router.history.push('./login');

最新更新