1

我尝试初始化第三方库在 React 钩子中我正在使用 useEffect 但我总是得到null 我尝试使用自定义钩子但我得到相同的结果(null)

任何想法?

这是我的代码https://stackblitz.com/edit/react-rg9uov

谢谢

4

2 回答 2

2

useEffect应该为 声明依赖数组ref,也不知道为什么const stage = useRef(null);要使用?stage可能只是一个组件状态。

 const [stage, setStage] = React.useState();
 const ref = useRef();

 useEffect(() => {
    if(ref.current){
      setStage(new Konva.Stage({
      container: ref.current, // id of container <div>
      width: 500,
      height: 300
    }))
    }

  },[ref]);
于 2020-04-07T15:01:33.803 回答
0

You're seeing null because the console.log is running before useEffect, if you put a console.log at the end of useEffect you'll see that Konva is initialized properly.

于 2020-04-07T14:56:51.293 回答