【问题标题】:React promise to end of useState HookReact 承诺结束 useState Hook
【发布时间】:2019-11-08 22:11:21
【问题描述】:

我正在使用上下文函数,并在其他 js 文件上调用该函数。但是 setThreeImdf 是 useState 函数。

上下文函数;

     const [threeImdf, setThreeImdf] = useState({});

     const createMap = (ref, width, height) => {
          const display_point = map.venue.features[0].properties.display_point.coordinates;
          const threeImdf = new ThreeImdf(
            ref,
            width,
            height,
            map,
            display_point
          );
          window.addEventListener("resize", () => {
            threeImdf.resize(window.innerWidth, window.innerHeight);
          });
          threeImdf.showLayer([0]);
          setThreeImdf(threeImdf);
        });
      };

Home.js useEffect 函数

const { map, createMap, threeImdf } = useContext(MapContext);

    useEffect( async () => {
        if (!_.isEmpty(map)) {
          createMap(mapRef, window.innerWidth, window.innerHeight);
          const data = threeImdf.getGrouppedObjectsByLayer(currentFloor);
          const layers = threeImdf.getOrdinalsNumber();
          setFloorCount(layers);
          setCategories(data);
        }
      }, []);

但是我在useEffect中运行上下文函数,返回给我三个Imdf not found。我想等待 setThreeImdf 钩子结束。我该怎么做?

【问题讨论】:

    标签: javascript reactjs promise async-await


    【解决方案1】:

    需要创建上下文

    const Context = React.createContext(MapContext);
    

    上下文是可见的,你需要将组件包装在:

    <Context.Provide>
       //You component
    </Context.Provider>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2021-03-17
      • 1970-01-01
      相关资源
      最近更新 更多