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