我想将我的 zustand 状态分解为更小的可重用对象;但是,记录在案的 zustand 模式似乎都涉及将操作提升到顶级存储对象。有没有办法允许内部对象发生突变,而不必为每个对象重复每个操作?
例如,假设我们有一个车辆对象:
function makeVehicle() {
return { going: false };
}
function startVehicle(vehicle) {
return { ...vehicle, going: true };
}
function stopVehicle(vehicle) {
return { ...vehicle, going: false };
}
我可以有一个包含两个命名车辆的状态
import { create } from 'zustand';
export default create(set => {
blueVehicle: makeVehicle(),
greenVehicle: makeVehicle()
});
但是,似乎如果我还想导出 mutators,我需要为每个对象重复每个操作,并带有相当多的样板:
import { create } from 'zustand';
export default create(set => {
blueVehicle: makeVehicle(),
startBlueVehicle: () => set(
state => ({ blueVehicle: startVehicle(state.blueVehicle) })
),
stopBlueVehicle: () => set(
state => ({ blueVehicle: stopVehicle(state.blueVehicle) })
),
greenVehicle: makeVehicle(),
startGreenVehicle: () => set(
state => ({ greenVehicle: startVehicle(state.greenVehicle) })
),
stopGreenVehicle: () => set(
state => ({ greenVehicle: stopVehicle(state.greenVehicle) })
)
});
有没有更简单的表达方式?