简体   繁体   English

反应:如何从异步 function 中保存价值并稍后使用

[英]React: How to save value from async function and use later

I have an async function that calls an api getting me the current role of a user.我有一个异步 function 调用 api 让我获得用户的当前角色。 Later on I want to attach that role to a variable.稍后我想将该角色附加到一个变量。 Here's my code这是我的代码

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

I'm new to react and having trouble with this.我是新手,对此有反应并遇到麻烦。 How can I set currentRole to the value in return roles ?如何将currentRole设置为return roles的值?

I would opt to save the information that you got from the API on a state我会选择将您从 API 获得的信息保存在 state 上

const [roles, setRoles] = useState();

const getRole = async () => {
        const response = await roleService.getRole();
        const roles = await response.role
        setRoles(roles);
    }

you can call the gerRole function on a useEffect like this您可以像这样在 useEffect 上调用 gerRole function

useEffect(() => {
getRole();
}, []);

or you can call the getRole function on a button click或者您可以单击按钮调用 getRole function

<button onClick={getRole}>Click me to get roles</button>

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

相关问题 如何将表单中的值存储在变量中以供以后在函数中使用? - How to store the value from a form in a variable for later use in a function? 如何在反应中从异步 function 中检索值? - How do I retrieve value from async function in react? 如何在 React Native 中从异步 JS function 返回变量的值 - How to return value of variable from async JS function in React Native 如何从 react-native 的异步函数中获取价值? - How to get value from async function in react-native? 如何从异步 function 获取返回值到 React Native 中的变量? - How to get a return value from async function to a variable in React Native? 如何获取并保存异步函数的值 - How to get value of async function and save it 如何在片段着色器中保存值以便以后使用它? - How to save a value inside a fragment shader to use it later? 如何将 mongodb findone 值保存到 javascript 变量以便稍后在 nodejs 上使用 - How to save mongodb findone value to a javascript variable to use it later on nodejs 如何从数组中删除对象并保存以供以后使用? - How to remove object from Array and save it for use later? 如何在本机反应中处理异步 function 响应并保存在 useState 中? - How to handle Async function response in react native and save in useState?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM