我正在使用 zustand 进行状态管理,并且在检索一次数据后,当组件状态发生变化时,我只尝试实时更新组件而不刷新页面。
这是我的商店
export const useStore = create((set) => ({
reservations: [],
getReservations: async () => {
const response = await axios.get(baseUrl);
set({ reservations: response.data });
},
setRev: (reservations) => {
set((state) => ({
...state,
reservations,
}));
},
addReservation: (reservation) => {
set((state) => ({ reservations: [...state.reservations, reservation] }));
},
removeReservation: (id) => {
set((state) => ({
reservations: state.reservations.filter(
(reservation) => id !== reservation._id
),
}));
},
}));
我尝试使用 useEffect 挂钩来检索数据,如下面的代码所示,我有另一个调用该addReservation
函数的组件。下面的代码导致无限调用useEffect,而不是仅在有更改时才更新const reservations
,当另一个组件调用该addReservation
函数时。
const getAllReservation = useStore((state) => state.getReservations);
const reservations = useStore((state) => state.reservations);
const reservationsRef = useRef(useStore.getState().reservations);
useEffect(() => {
getAllReservation()
useStore.subscribe(
(reservations) => (reservationsRef.current = reservations),
(state) => state.reservations
);
}, [reservations]);
我曾尝试这样拆分 useEffects,但需要再次刷新页面以显示更新的数据。(想要的结果是没有刷新)
useEffect(() => {
getAllReservation()
}, [])
useEffect(() => {
useStore.subscribe(
(reservations) => (reservationsRef.current = reservations),
(state) => state.reservations
);
}, [reservations]);
我尝试将[]
依赖数组作为 useEffect 钩子中的第二个参数,但效果不佳。
谢谢您的帮助。