簡體   English   中英

反應:如何從異步 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM