简体   繁体   English

如何从promise里面返回useEffect

[英]How to return from promise inside useEffect

I am creating my first custom hook.我正在创建我的第一个自定义钩子。 I would like the hook to return the deviceType which is the result of a Promise in the hook.我希望钩子返回deviceType ,它是钩子中Promise的结果。

Hook:钩:

export default function useDeviceType() {
  // Finds the user's device type and sets the
  // screen orientation appropriately.
  useEffect(() => {
    getDeviceTypeAsync().then((deviceType) => {
      const orientationPromise = setScreenOrientation(deviceType);
      return deviceType
    });
  }, []);
}

Use of hook:钩子的使用:

export default function DevelopmentScreen() {
  const deviceType = useDeviceType();
  console.log(deviceType)
  return null;
}

Console:安慰:

undefined不明确的

I may be having difficulty understanding the useEffect hook but I believe it should just fully run once here.我可能很难理解useEffect钩子,但我相信它应该在这里完全运行一次。

Is the item being returned still undefined because the Promise has not resolved?由于Promise尚未解决,被退回的项目是否仍然未定义? If so, then how am I able to use the deviceType inside setScreenOrientation ?如果是这样,那么我如何在setScreenOrientation中使用deviceType

When I console.log(deviceType) inside the useEffect hook I get the appropriate response:当我在useEffect钩子中使用console.log(deviceType)时,我得到了适当的响应:

2 2

Thank in advance for the help in understanding this!在此先感谢您对理解这一点的帮助!

Final Edit:最终编辑:

export default function useDeviceToSetOrientation() {
  const [orientation, setOrientation] = useState(null);
  useEffect(() => {
    getDeviceTypeAsync().then((type) => {
      const orientationPromise = setScreenOrientation(type);
      orientationPromise.then((data) => {
        setOrientation(data);
      })
    });
  }, []);
  return orientation
};

export default function DevelopmentScreen() {
  const orientation = useDeviceToSetOrientation();
  console.log(orientation)
  return null;
}

Output (correct): Output(正确):

4 4

export default function useDeviceType() {
  const [deviceType, setDeviceType] = useState();
  useEffect(() => {
    getDeviceTypeAsync().then((type) => {
      const orientationPromise = setScreenOrientation(type);
      setDeviceType(type);
    });
  }, []);
  return deviceType
}

This should fix the behavior and then deviceType will be accessible through const deviceType = useDeviceType();这应该可以修复该行为,然后可以通过const deviceType = useDeviceType(); deviceType deviceType . .

What you seem to be misunderstanding here is how returning values from useEffect work.您在这里似乎误解的是从useEffect返回值的工作原理。 You can read about ithere , but we actually use it to create cleanup functions that will run on our component's unmount.你可以在这里阅读它,但我们实际上使用它来创建将在我们的组件卸载时运行的清理函数。

Edit: you can also see in React's docs how custom hooks are supposed to return values.编辑:您还可以在React 的文档中看到自定义钩子应该如何返回值。

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

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