我正在尝试构建一个组件,该组件从 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';
}
}
);
};
谁能给点建议?如果是这样,非常感谢!
答案 0 :(得分:0)
因为你永远不应该那样做!查看 this 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>
对于类组件,您将使用生命周期方法来实现这一点(都在文档中 - 上面的链接)。