【问题标题】:Binding redux state to an object将 redux 状态绑定到对象
【发布时间】:2017-03-09 11:38:33
【问题描述】:

是否有一种既定的方法可以将 redux 状态绑定到对象?

我想做这样的事情:

MyApi.setStore(myReduxStore, 'stateVar')

我玩过传递各种 get/set 操作和存储侦听器,但它一团糟。

MyApi.getState = () => store.dispatch(getAction())
MyApi.setState = (state) => store.dispatch(setAction(state))
let currentState
store.subscribe(() => {
  let previousState = currentState
  currentState = store.getState().stateVar
  if(previousState !== currentState) {
    MyApi.stateListener(currentState)
  }
})

【问题讨论】:

  • 你想达到什么目的? Redux state 已经是对象了...
  • 我的 API 做了一些异步操作。我希望它向 redux 公开它的状态,以便可以在各种反应组件中获取它。
  • 知道每个reducer都会返回新的状态,你可以创建reducer来从你的API返回状态。

标签: javascript redux react-redux redux-thunk


【解决方案1】:

在 redux 中进行 api 调用的方法是使用像 redux-thunkredux-saga 这样的中间件。这样你就可以将 api 调用与 redux 分开,并在结果准备好时调度一个动作。

来自 redux-saga 自述文件的 API 调用示例:

import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'

// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
   try {
      const user = yield call(Api.fetchUser, action.payload.userId);
      yield put({type: "USER_FETCH_SUCCEEDED", user: user});
   } catch (e) {
      yield put({type: "USER_FETCH_FAILED", message: e.message});
   }
}

/*
  Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.
  Allows concurrent fetches of user.
*/
function* mySaga() {
  yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}

/*
  Alternatively you may use takeLatest.

  Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
  dispatched while a fetch is already pending, that pending fetch is cancelled
  and only the latest one will be run.
*/
function* mySaga() {
  yield takeLatest("USER_FETCH_REQUESTED", fetchUser);
}

export default mySaga;

然后你的 reducer 只会在 "USER_FETCH_REQUESTED" 上将加载状态设置为 true,在 "USER_FETCH_SUCCEEDED" 上更新状态并在 "USER_FETCH_FAILED" 上设置一些错误状态。

【讨论】:

  • 谢谢。我已经将 redux-thunk 用于各种涉及将至少一个操作映射到每个 api 方法的事情。如果将 api 配置为感知状态,则可能会减少其中的一些。
  • 我没有使用过 thunk,但至少在 sagas 中,你最终会得到很多样板代码。我一直在考虑编写一个可以执行的辅助函数:createApiHandler("USER_FETCH_REQUESTED", Api.fetchUser , "USER_FETCH_SUCCEEDED", "USER_FETCH_FAILED")
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多