我开始学习 React + hooks。我现在正在使用 useReducer。但是我在更新我的 useReducer 状态时遇到了问题。每次我想更新对象状态的 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
}
});
};