我正在构建一个 React 应用程序,我使用以下代码从 API 获取数据。
import './App.css';
import {useEffect, useState} from 'react';
function App() {
const [records, setRecords] = useState([]);
useEffect(()=>{
getData();
}, []);
const getData = async() => {
const response = await fetch('https://localhost:7280/api/Student/GetAll')
const recdata = await response.json
setRecords(recdata["data"])
}
return (console.log(records));
}
export default App;
当我检查网络调用时,API 返回以下响应
{
"data": [
{
"id": 1,
"firstName": "Harinda",
"lastName": "Vithana",
"email": "[email protected]",
"telephone": "0744896164",
"nic": "199400560123"
},
{
"id": 3,
"firstName": "John",
"lastName": "Cena",
"email": "[email protected]",
"telephone": "077164164",
"nic": "78452123545"
}
],
"success": true,
"message": ""
}
我是 React 新手,所以我不知道是什么导致了问题,也不知道这是否是获取数据的正确方法。如果我遗漏了一些明显的东西,请道歉。
您的代码看起来不错。但有一个小语法错误。
const getData = async() => {
const response = await fetch('https://localhost:7280/api/Student/GetAll')
const recdata = await response.json() // Corrected here
//const recdata = await response.json // Previously
setRecords(recdata["data"])
}
快乐编码!