在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 關(guān)于redux中dispatch異步action

關(guān)于redux中dispatch異步action

在redux中dispatch異步action,通常是1寫法。但是不理解1和2的區(qū)別,求指導(dǎo)!

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.
);
回答
編輯回答
墨小羽

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')返回的是下面的函數(shù)

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

第二步:調(diào)用第一步返回的函數(shù)并傳入相應(yīng)的參數(shù)

2018年8月4日 19:51