我一直使用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 })
);
}