我有一個從我的 Supabase 資料庫中獲取資料的異步函式,當呼叫它時,它會回傳一個帶有我查詢過的正確資料的承諾,但是當我嘗試在 React 組件中呼叫這個函式時,我不知道如何提取來自 Promise 的資料,然后獲取我查詢的字串。
我知道您無法在與您所稱的范圍相同的范圍內獲得承諾的結果,但我不確定如何解決這個問題。
我的代碼:
export async function getUserValue(uuid, value) {
const { data, error } = await supabase
.from('users')
.select('username').eq("id", "8f1693d3-c6d9-434c-9eb7-90882ea6ef28"); // hard coded values for testing purposes
return data;
}
我稱之為:
...
async function Sidebar(props) {
console.log(getUserValue("", ""))
return (
<div className={"sidebar"}>
<div className="sidebar-main">
<img className={"sidebar-main-picture"} src={profile_picture} alt="將資料從 Supabase 提取到 React 時使用 Promise"/>
<p className={"sidebar-main-name"}>Test</p>
...
結果
uj5u.com熱心網友回復:
在 React 組件中存盤資料的方式是定義和設定 state。
處理異步回應資料等副作用的正確位置是在效果掛鉤中
import { useEffect, useState } from "react";
function Sidebar(props) {
const [ user, setUser ] = useState(null); // initial value
useEffect(() => {
getUserValue("", "")
.then(users => {
setUser(users[0]) // your response is an array, extract the first value
})
.catch(console.error)
}, []); // empty array means run this once on mount
return user && ( // only display if `user` is set
<p>Hello, { user.username }</p> {/* just an example */}
);
}
我覺得這肯定已經被問過并回答過,但我找不到適用的副本。如果有人可以鏈接現有帖子,很高興洗掉此內容或將其標記為社區 Wiki。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/440235.html
標籤:javascript 反应 异步 超级基础
上一篇:資料庫內容更改時渲染頁面
