Where do I update the location after an async dispatch with react-router and redux

时光毁灭记忆、已成空白 提交于 2019-12-12 01:43:14

问题


The problem I have now is that I don't know how to get my location to update after "FETCH_USER_FULFILLED" was dispatched (see https://github.com/DDecoene/React-flux-example/blob/4ab1503dc92d28108f50481a293104ba5d15a29e/app/actions/userActions.js#L17)

What I'm trying to do, is to do a post to an API and when it is OK, switch to the index 'page'

I've tried redux-router too but I did not get it to work at all.


回答1:


I would suggest using react-router-redux. It comes with push and replace actions so you can dispatch them in your action creator. It's a cleaner way to handle route changes and you'll see proper actions in redux dev tools. Assuming you use redux-thunk middleware:

export const fetchUser = (username, password) => {
  return dispatch => {
    axios.post(Endpoints.userLogin, {username, password}).then((response) => {
      dispatch({type: "FETCH_USER_FULFILLED", payload: response.data});
      dispatch(push('/new_location'));
    });
  };
};



回答2:


probably the simplest solution is to use browserHistory.push() after dispatch:

import { browserHistory } from 'react-router';

...

axios.post(Endpoints.userLogin, {username, password})
  .then((response) => {
      dispatch({type: "FETCH_USER_FULFILLED", payload: response.data});
      browserHistory.push('your/index/route');

  })


来源:https://stackoverflow.com/questions/38995841/where-do-i-update-the-location-after-an-async-dispatch-with-react-router-and-red

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!