为什么这个异步函数没有 return 任何东西?

Why does this async function not return anything?

我有一个函数需要在我的应用程序启动时 运行。它基本上进行了几次 API 调用来获取用户信息、统计其消息并订阅套接字通道。

它是用React-query制作的。但它不执行任何 API 调用。函数 _getUserInformations 从未被触发,我的检查器的网络选项卡仍然无效。

服务器没有问题,路由正常。这是代码:

export default function App() {
  useEffect(() => {
    initializeUser();
  }, []);
  const user = userStore();
  
  return routes + app
  );
}

export const initializeUser = () => {
  try {
    const res = await getUserInformations();
    const user = res.data.user;
    updateUser(user);
    const { unreadConversations } = await hasUnreadConversations(user._id);
    updateunreadConversations(unreadConversations);
    getNotifications(user._id);
  } 
  catch (err) {
    return null;
  }
};

const _getUserInformations = async () => {
  try {
    const userToken = await api.get("/user-informations", {
      withCredentials: true,
    });
    return userToken;
  } catch (err) {
    throw new Error(err.message || "error.unknown");
  }
};

const getUserInformations: UserService["getUserInformations"] = () => {
  const { data } = useQuery("getUserInfos", () => _getUserInformations(), {
    cacheTime: 1000 * 60 * 60 * 24, // 24 hours
  });
  return data.data.user;
};

这里有什么问题?

这里还有一个沙盒重现了与 PokeApi 相同的问题:https://codesandbox.io/s/gifted-hill-tei88?file=/src/App.js

_getPokemon(模仿 _getUserInformations)也从未被调用...

挂钩只能在功能组件中使用。

例如在你的codesandbox代码中,如果你使用下面的代码,它会起作用。

export default function App() {
  const { data, isError } = useQuery("getpokemon", () => _getPokemon());
  console.log('data', data) //you can see the data printed.
  React.useEffect(() => initialize(), []);


  if (!data && !isError) return <Loading /> // Bonus Tip - data is fetching if both data and isError is undefined.

  return <div>hello</div>;
}

https://reactjs.org/docs/hooks-rules.html

Don’t call Hooks from regular JavaScript functions. Instead, you can:

✅ Call Hooks from React function components.

✅ Call Hooks from custom Hooks (we’ll learn about them on the next page).

还有...

Only Call Hooks at the Top Level Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top

level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls. (If you’re curious, we’ll explain this in depth below.)