反应 useEffect 清理功能

时间:2021-05-17 18:03:49

标签: reactjs

我有 post 组件,其中有 useEffect,其中照片设置在 state 中。如果我单击其他链接以进行快速操作,则会收到错误“无法在未安装的组件上执行 React 状态更新”。所以它告诉我需要清理,但无论我尝试在线阅读什么,我都无法弄清楚如何正确进行清理并且仍然出现相同的错误。这就是我现在所拥有的。


const ignore = useRef(true);
const [postImage, setPostImage] = useState();

useEffect(() => {
    if (ignore) {
      if (postPhoto) {
        storageRef
          .child(postPhoto)
          .getDownloadURL()
          .then((url) => {
            setPostImage(url);
          });
      }
    }

    if (pathname === "/profile" || pathname === `/profile/${params.user}`) {
      setShow(false);
    } else {
      setShow(true);
    }
    return () => (ignore.current = false);
  }, [postData]);

清理应该是什么样子的?这是我过去几周最难以理解的事情。

1 个答案:

答案 0 :(得分:1)

问题是在卸载组件时 setPostImage(url) 会运行。为避免此错误,请在更新状态之前检查 ignore.current 是否为 true

storageRef
       .child(postPhoto)
       .getDownloadURL()
       .then((url) => {
          if(ignore.current) setPostImage(url); //--> here
       });