绝对坚持您的减速器状态!
如果您坚持执行一系列操作,那么您将不得不在前端数据库中随意修改自己的操作。
示例:将一个reducer的状态持久保存到服务器
我们将从三种额外的操作类型开始:
// actions: 'SAVE', 'SAVE_SUCCESS', 'SAVE_ERROR'
我使用redux-thunk进行异步服务器调用:这意味着一个动作创建者函数可以
dispatch执行其他动作并检查当前状态。
该
save行动的创建者立即派遣一个动作(这样就可以显示在你的UI中的微调,或禁用“保存”按钮)。然后,一旦POST请求完成,它就会调度
SAVE_SUCCESS或执行一个
SAVE_ERROR操作。
var actionCreators = { save: () => { return (dispatch, getState) => { var currentState = getState(); var interestingBits = extractInterestingBitsFromState(currentState); dispatch({type: 'SAVE'}); window.fetch(someUrl, { method: 'POST', body: JSON.stringify(interestingBits) }) .then(checkStatus) // from https://github.com/github/fetch#handling-http-error-statuses .then((response) => response.json()) .then((json) => dispatch actionCreators.saveSuccess(json.someResponsevalue)) .catch((error) => console.error(error) dispatch actionCreators.saveError(error) ); } }, saveSuccess: (someResponsevalue) => return {type: 'SAVE_SUCCESS', someResponsevalue}, saveError: (error) => return {type: 'SAVE_ERROR', error}, // other real actions here};(NB
$.ajax完全可以代替这些
window.fetch东西,我只是不想为一个功能加载整个jQuery!)
减速器仅跟踪任何未完成的服务器请求。
function reducer(state, action) { switch (action.type) { case 'SAVE': return Object.assign {}, state, {savePending: true, saveSucceeded: null, saveError: null} break; case 'SAVE_SUCCESS': return Object.assign {}, state, {savePending: false, saveSucceeded: true, saveError: false} break; case 'SAVE_ERROR': return Object.assign {}, state, {savePending: false, saveSucceeded: false, saveError: true} break; // real actions handled here }}您可能想对
someResponsevalue从服务器返回的进行某些操作-可能是新创建的实体的ID等。
我希望这会有所帮助,到目前为止对我来说效果很好!



