微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

(React & Mobx & Leaflet) 等待然后没有按我预期的那样工作

如何解决(React & Mobx & Leaflet) 等待然后没有按我预期的那样工作

晚上好。

此组件的目的是创建一个observable curentLocation 获取数据的地图。 loadInitialLocation() 中的 newMap()useEffect() 应该只被调用一次,而 updateMap() 中的 autorun() 会在 obrservable curentLocation 发生变化时被调用

问题是:在 newMap() 完成其从服务器获取数据并将结果加载到 loadInitialLocation() 的工作之前,不应调用 observable curentLocation。现在当 newMap() 为空时调用 obrservable curentLocation

我在 useEffect() 中试过这个:

useEffect(() => {
    loadInitialLocation().then(newMap());
  },[]);

哪里constant loadInitialLocation:() => Promise<void>。我预计“newMap() 只会在 loadInitialLocation() 完成后运行”。

我也在 useEffect() 中尝试过这个:

useEffect(() => {
    const getCurLoc = async () => {
      await loadInitialLocation();
      newMap();
    }
    getCurLoc();
  },[]);

还有这个:

useEffect(() => {
    loadInitialLocation().then(newMap());
    autorun(() => {
      console.log("autorun here")
      updateMap();
    });
  },[]);

商店:

@observable currentLocation: ILocation | null = null;
@action loadInitialLocation = async () => {
      try {
        const currentLocation = await agent.Adventure.locationDetails();
        runInAction(() => {
          this.currentLocation = currentLocation;
          console.log("load currentLocation")
        });
      } catch (error) {
        throw error;
      }
    }
  };

组件:

const LeafletMap: React.FC = () => {
  var map: L.Map;
  const tilePixelSize = 32;
  const rootStore = useContext(RootStoreContext);
  const { openModal } = rootStore.modalStore;
  const { currentLocation,loadInitialLocation } = rootStore.mapStore;

  useEffect(() => {
    loadInitialLocation().then(newMap());
  },[]);

  autorun(() => {
    console.log("autorun here")
    updateMap();
  });

  const newMap = () => {
    if (currentLocation == null) {
      console.log("null currentLocation");
      return null;
    }
    // code
    // use currentLocation to load the initial map

    console.log("successfully init map");
  };

  const updateMap = () => {
    if (map == undefined) {
      return null;
    }
    console.log("update map");
    // code
  };
  console.log("add to dom");
  return <div id="map"></div>;
};

export default observer(LeafletMap);

如果我移动到任何其他页面并返回此页面,地图将被正确加载。我认为这是因为 oberservable currentLocation 已加载,因此 newMap() 不会到达 if (currentLocation == null) 并返回 null。

如何确保仅在 newMap() 完成后运行 loadInitialLocation()?我没有正确使用 async、await 和 then 吗?

解决方法

我没有使用正确的方式调用 newMap()

这应该是正确的方法:

useEffect(() => {
    loadInitialLocation().then(() => newMap());
  },[]);

这样,我们可以确保只有当我们从 mobx 操作中获得预期结果时,我们才能执行“then”。

useEffect(() => {
    loadInitialLocation().then((result) => {
      if (result) {
        newMap(result);
      }
    });
  },[loadInitialLocation])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。