以下示例資料將來自后端 API 呼叫。后端是flask,API 已經在后端就位。
const rows = [
{
name: "XYZ",
age: "12",
email: "[email protected]"
},
{
name: "David",
age: "13",
email: "[email protected]"
},
{
name: "abc",
age: "12",
email: "[email protected]"
}
]
如何將后端 API 與 React 集成?我是新手,所以我不知道我應該如何進行。
uj5u.com熱心網友回復:
在 React 中,您必須使用兩個鉤子 -useState和useEffect. 第一個將幫助您保留資料以便您可以使用它,第二個將幫助您獲取它。
function Component() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('your endpoint here').then(res => {
if (res.status === 200) {
return res.json();
} else {
// handle error
}
}).then(data => {
setData(data);
}).catch(err => {
// handle error
})
}, []);
if (data !== null) {
return <p>Data is here {data.length}</p>;
}
return <p>Loading the data</p>;
}
并且只是為了澄清我們需要使用,useEffect所以我們只在安裝組件時觸發一次請求。這是將[]依賴項串列用作鉤子的第二個引數的效果。
uj5u.com熱心網友回復:
您可以使用 axios 發送 api 請求。
const [state,setState] = useState()
useEffect(()=>{
axios.get(url)
.then(res=>setState(res.data))
.catch(err=>console.log(err))
},[])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399014.html
標籤:javascript 反应 休息 烧瓶
上一篇:JS腳本中的模板變數注入
