警告:效果函数不能返回除用于清理的函数之外的任何内容

我找不到我的错误为什么我应该使用清理,并在我使用 useefect 时返回任何内容我只想检查用户是否登录..?

useEffect(async () => {
    var item = await AsyncStorage.getItem("User");
    console.log(item);
    if (item == null || item == undefined) {
      props.navigation.navigate("Login");
    }
    else {
      var user = await JSON.parse(item);
      if(user.fullname=="admin"){
        props.navigation.navigate("AdminHP");
      }
      else{
        props.navigation.navigate("UserHP");
      }
    }
    console.log("effect");

  },[]);
stack overflow Warning: An effect function must not return anything besides a function, which is used for clean-up
原文答案
author avatar

接受的答案

useEffect(() => {
    async function check() {
      var item = await AsyncStorage.getItem("User");
    console.log(item);
    if (item == null || item == undefined) {
      props.navigation.navigate("Login");
    }
    else {
      var user = await JSON.parse(item);
      if(user.fullname=="admin"){
        props.navigation.navigate("AdminHP");
      }
      else{
        props.navigation.navigate("UserHP");
      }
    }
    console.log("effect");
    }

    check()
  }, [])

答案:

作者头像

I had the same problem and from what I understand:

It is recommended that you do not send an async function as a direct callback of useEffect, but you can pass a callback that inside it you declare an async function

    useEffect(() => {
        async function func() {
            await method()
        }
    }, [])
作者头像

Though the answer provided by Emran Quedan is correct, It lacks an explanation, As martin has mentioned in the comment, the root issue is because React’s useEffect hook expects a cleanup function returned from its callback which is called when the component unmounts. Using an async function like

useEffect(async () => {

},[])

here will cause a bug because when we call async callback function of the useEffect is called, Promise is returned instead of function. to solve the issue slightly elegant syntax is like

useEffect(() => {
 (async () => {

    //Put your logic here

  })();

  }, [])```

In the above syntax, `async` function is defined and immediately called.