2017-03-09 69 views
0

是否存在将redux状态绑定到对象的既定方法?将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) 
    } 
}) 
+0

你想达到什么目的? Redux状态已经是对象... – Andrey

+0

我的API做一些异步的东西。我希望它能将它的状态暴露给redux,所以它可以在各种反应组件中找到。 – Simon

+0

知道每个reducer都返回新状态,您可以创建将从您的API返回状态的reducer。 – Andrey

回答

0

做API调用终极版的方法是使用一个中间件像redux-thunkredux-saga。这样,您可以将api调用与redux分开,并在结果准备就绪时发送操作。从终极版 - 传奇自述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; 

那么你的减速将只设置负载状态真正的“USER_FETCH_REQUESTED”,更新的“USER_FETCH_SUCCEEDED”状态和设置一些错误状态“USER_FETCH_FAILED”。

+0

谢谢。我使用了redux-thunk来处理各种涉及将至少一个动作映射到每个api方法的各种事情。如果api被配置为知道状态,那么可能会减少一些。 – Simon

+0

我还没有使用过thunk,但至少有了传奇故事,你最终得到了很多样板代码。我一直在思考写一个辅助函数会的只是做: 'createApiHandler( “USER_FETCH_REQUESTED”,Api.fetchUser, “USER_FETCH_SUCCEEDED”, “USER_FETCH_FAILED”)' – OlliM