简体   繁体   English

为什么state设置后还是null?

[英]Why is the state still null even after setting it?

I'm trying to set an object then use it immediately but it is saying that it's null.我正在尝试设置一个 object 然后立即使用它,但它说它是 null。 I can observe in debug mode that the instantiated object is not null.我可以在调试模式下观察到实例化的 object 不是 null。

I could just use the instantiated objected instead of the constant but I was advised not to.我可以只使用实例化的对象而不是常量,但我被建议不要。

import { useState, useEffect } from "react";
import { loadModules } from "@esri/react-arcgis";

const TestLayer = props => {
  const [layer, setLayer] = useState(null);
  useEffect(() => {
    loadModules(["esri/layers/GraphicsLayer"])
      .then(([GraphicsLayer]) => {
        const graphicsLayer = new GraphicsLayer();
        setLayer(graphicsLayer);
        props.map.layers.add(layer); //layer is still null
      });
  }, []);

  return null;
};

export default TestLayer;

Yeah, it's async like the comments suggest.是的,就像评论所暗示的那样,它是异步的。 The good news is that where you're trying to access it synchronously is the same place that you have access to the original object, so you can just use it directly:好消息是,您尝试同步访问它的位置与您可以访问原始 object 的位置相同,因此您可以直接使用它:

import { useState, useEffect } from "react";
import { loadModules } from "@esri/react-arcgis";

const TestLayer = props => {
  const [layer, setLayer] = useState(null);
  useEffect(() => {
    loadModules(["esri/layers/GraphicsLayer"]).then(([GraphicsLayer]) => {
      const graphicsLayer = new GraphicsLayer();
      setLayer(graphicsLayer);
      props.map.layers.add(graphicsLayer); // Don't need to access state here
    });
  }, []);

  return null;
};

export default TestLayer;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM