我已经概述了几种可能从 Web 服务访问状态的方法,但我不知道在 react-redux 应用程序中哪一种是正确的,或者下面是否列出了正确的方法。
上下文:
最初,我有一个 API.js
文件作为网络服务的基础。然后我会将其导入到我的 Action 文件中。这很顺利直到我需要从 API.js
访问状态(更具体地说,是我的 header 所需的状态中的网络 token )。我尝试导入我的商店,但它返回了 undefined
。然后我意识到我有一个循环依赖:
api -> store -> reducers -> components -> actions
自定义中间件
我想知道这是否可以接受。我放弃了我的 API.js
。我用它来自动修改具有特定操作类型的传出网络调用。这是我的中间件堆栈的样子:
const middleware = applyMiddleware(
myCustomModifyRequestMiddleware,
thunk,
. . .
myCustomModifyRequestMiddleware
基本上是这样的:
const myCustomModifyRequestMiddleware = store => next => action {
if(action.type === 'MODIFY_ME') {
//Dispatch an FSA
store.dispatch({
type: action.payload.actual_type,
payload: axios.create({ . . .
meta: action.meta
})
}
return next(action)
}
现在我的中间件中有了业务逻辑!
然后我就可以有一个名为 API_ActionCreator
的 Action 创建器。但是,嘿,如果我只是想使用 Action 创建器,为什么不...
Think it
使用 thunk 我可能只需要类似 API_ActionCreator.js
的东西:
const apiActionCreator = (actual_type, url, data . . .) {
return (dispatch, store) {
//Now I can get the state...
store.getState()
//Return an FSA
return {
type: actual_type,
payload: axios.create...
现在我可以将我的 API_ActionCreator
导入到我的操作中,而无需任何循环依赖。
订阅商店?
另一种方法是让 Web 服务是有状态的;订阅 store
中的商店或 web 服务
,如果我在我的操作中调用我的 web 服务时能以某种方式避免遇到循环依赖的话。
TLDR; 当然,这都是实验性的,尽管我能够让中间件工作。
我不知道哪一个是最可行的方法,是否有更像 redux 的方法来做到这一点?
最佳答案
Thunk action creators 和集中式中间件都是在 Redux 中管理 API 调用的标准方法,同时可以访问 dispatch
和 getState`。两者都可以。
有关更多信息,请参阅 Dan 在 managing async behavior in Redux 上的回答和 why thunks and other middleware are useful for async work ,以及我的 React/Redux links list 的 Redux 副作用部分中的其他文章.您可能还对 Redux middleware for making network requests 的列表感兴趣在我的 Redux addons catalog .
关于javascript - Redux:从 Web 服务访问状态的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101207/