next.js 我们可以在其他zustand商店触发事件吗?React

ki1q1bka  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(114)

我是完全新的zustand,我很想知道是否有可能作出改变,以一个商店从内部的另一个?如果是,请完成修改increasePopulation函数,使其也增加forestStore中的动物。谢啦,谢啦

const bearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  //should also increase animals count in forestStore
}))

const forestStore = create((set) => ({
  animals: 0,
}))

字符串

bq9c1y66

bq9c1y661#

const bearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => {
    // Get the current state of the forestStore
    const forestState = forestStore.getState();

    // Update the state of forestStore with increased animals count
    forestStore.setState({ animals: forestState.animals + 1 });

    // Update the bears count in bearStore
    set((state) => ({ bears: state.bears + 1 }));
  },
}));

const forestStore = create((set) => ({
  animals: 0,
}));

export { bearStore, forestStore };

字符串

相关问题