0

我正在使用 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 钩子中的第二个参数,但效果不佳。

谢谢您的帮助。

4

1 回答 1

0

React 无法检测到 Ref 内部的变化。因此需要将更新的预订作为道具传递或保存在本地状态。

文档

subscribe 功能允许组件绑定到状态部分 ,而无需强制重新渲染更改。最好将它与 useEffect 结合使用,以便在卸载时自动取消订阅。当您被允许直接改变视图时,这可能会对性能产生巨大影响。

  const useStore = create(set => ({ scratches: 0, ... }))
    function Component() {
      // Fetch initial state
      const scratchRef = useRef(useStore.getState().scratches)
      // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference
      useEffect(() => useStore.subscribe(
        scratches => (scratchRef.current = scratches),
        state => state.scratches
      ), [])
于 2021-07-20T09:56:27.057 回答