简体   繁体   English

将Redux状态绑定到对象

[英]Binding redux state to an object

Is there an established way to bind a redux state to an object? 是否存在将redux状态绑定到对象的既定方法?

I want to do something like this: 我想做这样的事情:

MyApi.setStore(myReduxStore, 'stateVar')

I've played with passing various get/set actions and store listeners but it's a mess. 我玩过传递各种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)
  }
})

The way to do api calls in redux is to use a middleware like redux-thunk or redux-saga . 在redux中进行api调用的方法是使用redux-thunkredux-saga之类的中间件。 That way you separate the api call from redux and just dispatch an action when the result is ready. 这样,您可以将api调用与redux分开,并在结果准备好后立即调度操作。

Example of an API call from redux-saga readme: 来自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;

Then your reducer will just set loading state to true on "USER_FETCH_REQUESTED", update the state on "USER_FETCH_SUCCEEDED" and set some error state on "USER_FETCH_FAILED". 然后,减速器将在“ USER_FETCH_REQUESTED”上将加载状态设置为true,在“ USER_FETCH_SUCCEEDED”上更新状态,并在“ USER_FETCH_FAILED”上设置一些错误状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM