Definitely persist the state of your reducers!
如果你保留了一系列动作,你将永远无法在前端修改你的动作,而不需要在你的prod数据库中翻来覆go .
Example: persist one reducer's state to a server
我们将从三种额外的动作类型开始:
// actions: 'SAVE', 'SAVE_SUCCESS', 'SAVE_ERROR'
我使用redux-thunk来执行异步服务器调用:这意味着一个action creator函数可以执行dispatch
个额外的操作并判断当前状态.
save
action creator会立即发送一个操作(这样您就可以显示微调器,或者在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
};
(注:$.ajax
完全可以代替window.fetch
,我只是不想为一个函数加载整个jQuery!)
reducer只跟踪任何未完成的服务器请求.
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等等.
我希望这能有所帮助,到目前为止对我来说效果很好!