关于redux中dispatch异步action

在redux中dispatch异步action,通常是1写法。但是不理解1和2的区别,求指导!

const fetchPosts = (postTitle) => (dispatch, getState) => {
  dispatch({ type: 'FETCH_POSTS_REQUEST' });
  return fetch(`/some/API/${postTitle}.json`)
    .then(response => response.json())
    .then(json => dispatch(receivePosts(json)));
  };
};

//1
store.dispatch(fetchPosts('reactjs')).then(() =>
     //do sth.
);

//2
fetchPosts('reactjs').then(() =>
     //do sth.
);
阅读 3.8k
1 个回答

2的写法有误,因为fetchPost('reactjs')的返回值并不是一个promise
1为什么可以这样写?
以使用redux-thunk为例,封装后的dispatch方法其实是下面的功能(完整代码请参见github)

function (action) {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }
    
    return next(action);
};

所以store.dispatch(fetch('reactjs'))拆成两步来看
第一步:fetch('reactjs')返回的是下面的函数

(dispatch, getState) => {
  dispatch({ type: 'FETCH_POSTS_REQUEST' });
  return fetch(`/some/API/${postTitle}.json`)
    .then(response => response.json())
    .then(json => dispatch(receivePosts(json)));
  };
};

第二步:调用第一步返回的函数并传入相应的参数

推荐问题