How should I update redux store during a react-router transition?

后端 未结 2 2028
挽巷
挽巷 2021-02-15 02:35

I\'m facing an issue on how to update store when a react-router transition occurs.

In my current implementation (below), update store before rendering next page. The iss

2条回答
  •  梦谈多话
    2021-02-15 03:23

    You can use redux-thunk middleware to dispatch multiple actions one after another

    See the awesome redux doc #Async Actions section for more!

    So your fetch data action creator will look something like this:

    function fetchSomeData(path) {
      return dispatch => {
        // first dispatch a action to start the spinner
        dispatch(fetchStarted(path))
    
        return superagent.get(path)
          .set('Accept', 'application/json')
          .end((err, res) => {
            if (err) {
              dispatch(fetchDataError(err)) // handle error
            } else {
              let pageData = res && res.body || {};
              dispatch(fetchSuccess(pageData)); // do whatever you want when fetch is done here
              // such as this action from redux-simple-router to change route
              dispatch(pushPath('/some/path'))
          });
      }
    }
    

    As you can see, by simply doing store.dispatch(fetchSomeData('somePath')), it will automatically first call fetchStarted to show spinner, and when the process is done, call fetchSuccess(path) to hide spinner, update state, rerender...etc, or call fetchError(err) to show an error message, and you can call actions to change routes anywhere in this process!

    (you don't need redux-simple router if you don't like it, you can call history.pushState(null, '/some/path') to change route, I just found redux-simple-router really handy, because you don't need to pass the history everywhere, plus you have a UPDATE_PATH action you can listen to if you want to track route changes)


    Furthermore, I recommend redux-simple-router when you use react-router with redux, it allows you to watch route changes with the UPDATE_PATH action type, and pushPath action to change route. Also, I notice you're using an out-dated version of react-router...

    If you want to use the latest version of react-router with redux-simple-router (together with redux-thunk), check out this repo!

    you can find its store configuration, router setup in these files:

    src/main.js                 // calls reactDOM.render(, ...) to render 
    src/containers/Root.js      //  is a wrapper for react-redux 
    src/redux/configureStore.js // store configuration, how redux-thunk middleware is configured
    src/routes/index.js         // routes are defined here
    

提交回复
热议问题