为什么要重新考虑thunk而不是store.dispatch / store.getState()

时间:2020-04-11 16:08:50

标签: redux react-redux middleware redux-thunk

我一直使用redux-thunk或某种中间件来授予我对dispatch/getState的访问权限,但是我有一个问题一直困扰着我。当我们可以import store并呼叫store.dispatch()/store.getState()时为什么要使用它。

以后的修改:

作为一个简单的例子,这是原始代码:

function loadData(userId) {
  return dispatch => fetch(`http://data.com/${userId}`) // Redux Thunk handles these
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

基本上,我要问的是为什么将其重写为:

import store from 'our-store';

function loadData(userId) {
  return fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => store.dispatch({ type: 'LOAD_DATA_SUCCESS', data }),
      err => store.dispatch({ type: 'LOAD_DATA_FAILURE', err })
    );
}

0 个答案:

没有答案