简体   繁体   English

在 useEffect 钩子的 if 条件内调用异步 function

[英]Calling an async function inside the if condition of useEffect hook

How can I call a redux action inside the if block of useEffect hook:如何在useEffect钩子的 if 块中调用 redux 操作:

useEffect(async () => {
    if (nameId && selectedGroup === 'AGM') {
        const subPeople = await getSubPeople(nameId);
    }
}, [nameId, selectedGroup]);

I have two select boxes.我有两个 select 盒子。 If the person types in the name select box, I store the selected id of name in the nameId state.如果人员在name select 框中键入,我将选定的name id 存储在nameId state 中。 If user selects a group, I store it in selectedGroup , so only if both conditions match I need to call an API endpoint to get the subPeople .如果用户选择一个组,我将其存储在selectedGroup中,因此只有当两个条件匹配时,我才需要调用 API 端点来获取subPeople

If I comment this code there is no error.如果我评论此代码,则没有错误。 How can I make the snippet work?我怎样才能使片段工作?

You can move the async logic into a separate function and call it inside useEffect , since useEffect 's callback can't be async itself:您可以将异步逻辑移动到单独的 function 中并在useEffect中调用它,因为useEffect的回调本身不能是异步的:

useEffect(() => {
  const getPeople = async () => {
    if (nameId && selectedGroup === 'AGM') {
      const subPeople = await getSubPeople(nameId);
      return subPeople; // Or set the state, etc.
    }
  }
  getPeople(); 
}, [nameId, selectedGroup]);

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

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