【问题标题】:Returning a value from an Async Function. AWS/React从异步函数返回一个值。 AWS/反应
【发布时间】:2021-02-18 15:06:36
【问题描述】:

我正在尝试构建一个组件,该组件可从 Amazon AWS/Amplify 检索完整的用户列表,并通过映射函数在表格中显示所述结果。到目前为止一切顺利。

但是,对于第 4 列,我需要调用第二个函数来检查用户是否属于任何组。我已经将该功能作为按钮/onClick 事件进行了测试 - 它可以工作(console.logging 输出)。但是在渲染表格数据的时候直接调用它不会返回任何东西。

这是我在 return 语句中包含的内容(在 map 函数中)

<td>={getUserGroups(user.email)}</td>

然后调用这个函数:

const getUserGroups = async (user) => {
    const userGroup = await cognitoIdentityServiceProvider.adminListGroupsForUser(
      {
        UserPoolId: '**Removed**',
        Username: user,
      },
      (err, data) => {
        if (!data.Groups.length) {
          return 'No';
        } else {
          return 'Yes';
        }
      }
    );
  };

谁能给点建议?非常感谢提前!

【问题讨论】:

    标签: javascript reactjs amazon-web-services amplify


    【解决方案1】:

    因为你永远不应该那样做!查看thisReact 文档以更好地了解应该如何以及在何处进行 AJAX 调用。

    有多种方法可以解决您的问题。例如,添加用户组(或您需要从后端获取的任何内容) 作为状态,然后调用后端,然后使用响应更新该状态,然后 React 将重新渲染您的组件相应地。

    以钩子为例,但只是为了解释这个想法:

    const [groups, setGroups] = useState(null); // here you will keep what "await cognitoIdentityServiceProvider.adminListGroupsForUser()" returns
    
    useEffect(() => {}, [
        // here you will call the backend and when you have the response
        // you set it as a state for this component
        setGroups(/* data from response */);
    ]);
    

    你的组件(列,随便)应该使用groups

    <td>{/* here you will do whatever you need to do with groups */}</td>
    

    对于类组件,您将使用生命周期方法来实现这一点(全部在文档中 - 上面的链接)。

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 2021-04-10
      • 2022-01-14
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2020-09-12
      相关资源
      最近更新 更多