我有许多动作创建者,如果从服务器返回的响应是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);
答案 0 :(得分:3)
制作history.js
个文件
import createHistory from 'history/createHashHistory'
export default createHistory()
在action.js
文件中
import history from './history'
history.push('/abc')
资料来源:Github https://github.com/ReactTraining/react-router/issues/3498
答案 1 :(得分:0)
// this.props.history.push( '/登录');在这里,我需要访问历史
将props传递给fetchGroups
export function fetchGroups(props) {
...
}
尝试props.router.history.push('./login');