0

我正在尝试构建一个组件,该组件从 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';
        }
      }
    );
  };

任何人都可以建议吗?非常感谢提前!

4

1 回答 1

0

因为你永远不应该那样做!查看这个React 文档,以更好地了解应该如何以及在何处进行 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>

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

于 2021-02-18T15:13:42.297 回答