[英]How to store the value from a form in a variable for later use in a function?
[英]React: How to save value from async function and use later
我有一个异步 function 调用 api 让我获得用户的当前角色。 稍后我想将该角色附加到一个变量。 这是我的代码
const getRole = async () => {
const response = await roleService.getRole();
const roles = await response.role
return roles
}
...........
const currentRole = getRole() //I want this to be the value from return roles
我是新手,对此有反应并遇到麻烦。 如何将currentRole
设置为return roles
的值?
我会选择将您从 API 获得的信息保存在 state 上
const [roles, setRoles] = useState();
const getRole = async () => {
const response = await roleService.getRole();
const roles = await response.role
setRoles(roles);
}
您可以像这样在 useEffect 上调用 gerRole function
useEffect(() => {
getRole();
}, []);
或者您可以单击按钮调用 getRole function
<button onClick={getRole}>Click me to get roles</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.