简体   繁体   English

根据 state 变量运行 useEffect 挂钩的正确方法是什么?

[英]What is the corrct way of running useEffect hook depending on state variable?

I am writing a camera app.我正在写一个相机应用程序。 So when the user goes to the camera page they are provided with the option to grant camera permissions or not.因此,当用户进入相机页面时,他们可以选择是否授予相机权限。 I am saving their decision in variable const [hasPermission, setHasPermission] = useState(null);我将他们的决定保存在变量const [hasPermission, setHasPermission] = useState(null); My current use effect function:我目前使用效果function:

useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      const audioPermissions = await Audio.requestPermissionsAsync();
      if (
        cameraPermissions.status === "granted" &&
        audioPermissions.status === "granted"
      ) {
        setHasPermission(true);
      }
    })();
  }, []);

This currently works correctly when the user runs the app for the very first time - they grant permission, and thats it - I can use the camera!当用户第一次运行应用程序时,这目前可以正常工作 - 他们授予权限,就是这样 - 我可以使用相机!

However..... what if they dont grant permission.但是.....如果他们不授予许可怎么办。 They ecide not to use the camera, they deny access and later on they change their mind.. For instance 5 mins later, they open the "camera" page again and want to grant a permission.他们决定不使用相机,他们拒绝访问,后来他们改变了主意。例如 5 分钟后,他们再次打开“相机”页面并想要授予权限。 Here is my problem.这是我的问题。 As it is in the current situation useEffect , ie the request to use the camera will show only once, when you initially load the page.在当前情况下useEffect ,即使用相机的请求将只显示一次,当您最初加载页面时。 How do I force it to pop up again if the user hasnt granted permissions yet?如果用户尚未授予权限,我如何强制它再次弹出?

I tried the following:我尝试了以下方法:

useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      const audioPermissions = await Audio.requestPermissionsAsync();
      if (
        cameraPermissions.status === "granted" &&
        audioPermissions.status === "granted"
      ) {
        setHasPermission(true);
      }
    })();
  }, [hasPermission === null]);

but it didnt work.但它没有用。 Any suggestions?有什么建议么?

You only need to pass the variable that matters.您只需要传递重要的变量。 No need to check anything else.无需检查其他任何内容。

  }, [hasPermission]);

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

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