@H_404_1@对于给定的reducer,我的redux状态树通常看起来像这样:
@H_404_1@
{
someField: 'some value',// ... more fields
Metadata: {
pending: false,fetched: true,}
}
@H_404_1@通常,当我执行异步请求时,我会触发SOME_ACTION_REQUEST操作,该操作将Metadata.pending属性设置为true.当匹配的SOME_ACTION_RESPONSE或SOME_ACTION_ERROR事件稍后发生时,它会再次重置为false.
@H_404_1@但是,我更新状态的方式有点冗长:
@H_404_1@
case actions.SOME_ACTION_REQUEST: {
return {
...state,Metadata: { ...state.Metadata,pending: true },};
}
@H_404_1@有更简单的方法吗?
@H_404_1@Object.assign({},state,{Metadata:{pending:true}})也不是很易读.最佳答案
您可以使用reducer的嵌套结构.
@H_404_1@如果有一个函数/ reducer命名元数据,请调用它来更改字段.
@H_404_1@示例代码
@H_404_1@
const Metadata = (state = [],action = {}) => {
switch (action.type) {
case actions.SOME_ACTION_REQUEST::
return {...state,...action.payload.Metadata};
default:
return state;
}
};
const someReducer = (state = initalState,action = {}) => {
let Metadata = {};
switch (action.type) {
case actions.SOME_ACTION_REQUEST: {
Metadata = Metadata(state.Metadata,action)
return {
...state,...Metadata
};
}
}
};