我开始学习 React + 钩子了。我现在正在使用Reducer。但是我在更新我的使用Reducer状态时遇到问题。每次我想更新对象状态上的 1 个字段时,所有其他字段都将被删除。
我的解决方案是将它们所有现有值传递给它们,即使我只需要更新 1 个字段。有没有更有效的方法?
这是我的解决方案:
const initialState = {
filter: {
text: "Filter",
list: [],
isActive: false,
message: "",
},
apiList: []
};
const reducer = (state, action) => {
switch (action.type) {
case "SET_FILTER_LIST":
return {
...state,
filter: { ...state.filter,
list: action.payload.list,
isActive: action.payload.isActive,
message: action.payload.message,
text: action.payload.text,
}
};
default:
return state;
}
};
//BELOW - I just want to pass the e.target.textContent to text field. To avoid deleting the other fields. I re-pass all the existing value so it wont get deleted.
const onSelect = e => {
let filter = e.target.textContent;
dispatch({
type: 'SET_FILTER_LIST',
payload: {
list: state.filter.list,
text: filter,
message: state.filter.message,
isActive: state.filter.isActive
}
});
};
您可以使用下一个代码:
return {
...state,
filter: {
...state.filter,
...action.payload,
}
};
如果我理解你,你已经有了答案:
return {
...state,
filter: {
...state.filter,
text: action.payload
}
}
然后仅将文本字段传递到有效负载中