首页 > 解决方案 > Mobx - 更改依赖项列表中的项目时未执行 UseEffect 挂钩

问题描述

我是 React 和 Mobx 的新手。

我希望下面代码中的 useEffect 挂钩在日期更改时执行。日期变量在商店内。每当我更改日期时,我希望组件中的 useEffect 能够执行,但它仅在组件首次初始化时执行。

我将商店作为一项添加到 useEfftcts 依赖项列表中,但没有运气。任何帮助将不胜感激。

这是我的组件

const TeamDashboard: React.FC<IProps> = ({ teams, teamName, teamSchedule }) => {
  const teamsStore = useContext(TeamsStore);
  const datesStore = useContext(DatesStore);

  let teamIds: number[] = [];

  useEffect(() => {
    teams.map((team) => {
      teamIds.push(team.id);
    });

    teamsStore.loadScheudle(
      teamSchedule,
      teamIds,
      datesStore.startDate,
      datesStore.endDate
    );
  }, [datesStore]);

  return (
    <Container></Container>
  );
};
export default observer(TeamDashboard);

这是我的约会商店

class DatesStore {
    @observable startDate: Date = new Date();
    @observable endDate: Date = new Date('2021-04-05');

    @action setStartDate = (event: any, data: any, ) => {
        data.value > this.endDate
        ? this.startDate = new Date()
        : this.startDate = data.value === null ? seasonStartDate : data.value;
    }

    @action setEndDate = (event: any, data: any) => {
        console.log(data.value);
        this.endDate = data.value === null ? seasonEndDate : data.value;
    }
}

export default createContext(new DatesStore())

标签: reactjsuse-effectmobx

解决方案


利用 Mobx 版本 6 中的 makeAutoObservable 并删除 action 和 observables 装饰器解决了 useEffect 以在我的商店中更改日期时执行。下面是我的代码现在是如何设置的。

日期商店

export default class DatesStore {
    startDate: Date = new Date();
    endDate: Date = new Date();

    constructor() {
        this.endDate.setDate(this.startDate.getDate() + parseInt('30'));
        makeAutoObservable(this);
    }

    setStartDate = (event: any, data: any, ) => {
        data.value > this.endDate
        ? this.startDate = new Date()
        : this.startDate = data.value === null ? seasonStartDate : data.value;
    }

    setEndDate = (event: any, data: any) => {
        this.endDate = data.value === null ? seasonEndDate : data.value;
    }
}

存储所有商店的根商店和一个自定义挂钩以使用我的组件中的商店

interface Store {
    teamsStore: TeamsStore,
    datesStore: DatesStore
}

export const store: Store = {
    teamsStore: new TeamsStore(),
    datesStore: new DatesStore()
}

export const StoreContext = createContext(store);

export function useStore() {
    return useContext(StoreContext)
}

有问题的组件

const TeamDashboard: React.FC<IProps> = ({ teams, teamName, teamSchedule }) => {
  const { teamsStore, datesStore } = useStore();

  teams.slice().sort((a, b) => b.points - a.points);
  let teamIds: number[] = [];

  useEffect(() => {
    teams.map((team) => {
      teamIds.push(team.id);
    });

    teamsStore.loadScheudle(
      teamSchedule,
      teamIds,
      datesStore.startDate,
      datesStore.endDate
    );
  }, [datesStore.startDate, datesStore.endDate]);

  return (
    <Container></Container>
  );
};
export default observer(TeamDashboard);

推荐阅读