React and Redux: redirect after action

后端 未结 6 1398
孤城傲影
孤城傲影 2020-12-30 01:43

I develop a website with React/Redux and I use a thunk middleware to call my API. My problem concerns redirections after actions.

I really do not know how and where

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 02:06

    Definitely do not redirect from your reducers since they should be side effect free. It looks like you're using api-redux-middleware, which I believe does not have a success/failure/completion callback, which I think would be a pretty useful feature for the library.

    In this question from the middleware's repo, the repo owner suggests something like this:

    // Assuming you are using react-router version < 4.0
    import { browserHistory } from 'react-router';
    
    export function deleteItem(id) {
      return {
        [CALL_API]: {
          endpoint: `item/${id}`,
          method: 'DELETE',
          types: [
            DELETE_ITEM_REQUEST, 
            {
              type: DELETE_ITEM_SUCCESS,
              payload: (action, state, res) => {
                return res.json().then(json => {
                  browserHistory.push('/your-route');
                  return json;
                });
              },
            },
            DELETE_ITEM_FAILURE
          ]
        },
        id
      }
    };
    

    I personally prefer to have a flag in my connected component's props that if true, would route to the page that I want. I would set up the componentWillReceiveProps like so:

    componentWillReceiveProps(nextProps) {
      if (nextProps.foo.isDeleted) {
        this.props.router.push('/your-route');
      }
    }
    

提交回复
热议问题