Javascript 将redux状态绑定到对象
是否有一种将redux状态绑定到对象的既定方法 我想这样做:Javascript 将redux状态绑定到对象,javascript,redux,react-redux,redux-thunk,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.su
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中进行api调用的方法是使用诸如或之类的中间件。通过这种方式,您可以将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\u FETCH\u REQUESTED”上将加载状态设置为true,在“USER\u FETCH\u Successed”上更新状态,并在“USER\u FETCH\u FAILED”上设置一些错误状态即可。您希望实现什么?Redux状态已经是对象了…我的API做了一些异步的事情。我想让它向redux公开它的状态,这样就可以在各种react组件中获取它。知道每个reducer都返回新状态,您可以创建一个reducer,它将从您的API返回状态。谢谢。我使用redux thunk进行了很多工作,其中包括将至少一个操作映射到每个api方法。如果api被配置为可以感知状态,也许其中一些可以减少。我没有使用thunk,但至少在sagas中,您最终会得到很多样板代码。我一直在考虑编写一个助手函数,它只需执行以下操作:
createApiHandler(“USER\u FETCH\u REQUESTED”,Api.fetchUser,“USER\u FETCH\u successed”,“USER\u FETCH\u FAILED”)