将redux状态绑定到对象

时间:2017-03-09 11:38:33

标签: javascript redux react-redux redux-thunk

是否存在将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)
  }
})

1 个答案:

答案 0 :(得分:0)

在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”上设置一些错误状态。

相关问题