我不明白需要像redux-thunk
之类的东西。从我所了解的thunk
是一个返回函数的函数。包装的表达式和中间件的使用对我来说似乎更多地混淆了正在发生的事情。从redux-thunk
的示例代码为什么使用redux-thunk?
import thunk from 'redux-thunk';
// Note: this API requires [email protected]>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
// Meet thunks.
// A thunk is a function t hat returns a function.
// This is a thunk.
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
// Thunk middleware lets me dispatch thunk async actions
// as if they were actions!
store.dispatch(
makeASandwichWithSecretSauce('Me')
);
上面的代码可以更简洁的书面和直观的措施:
fetchSecretSauce().then(
sauce => store.dispatch(makeASandwich('Me', sauce)),
error => store.dispatch(apologize('The Sandwich Shop', forPerson, error))
)
我的问题是什么需要的是redux-react
实现,它是如何在类似的现有解决方案提高到上面的例子。
说你需要做的API调用,您可以编写一个解决或拒绝承诺的thunk,并相应地调度SUCCESS或FAIL动作,并且从组件内部执行所有需要做的事情就是loadMyThunk() - 所有调度的动作都被抽象为thunk。我有一个lib'redux-entity',它使用了这样的模式:https://github.com/mikechabot/redux-entity/blob/master/src/thunk.js – lux