我想从API中获取数据,然后将其打印出来,或者在我的react组件的返回语句中显示它,这样我就可以有一个从API中获取数据的p元素。问题是usestate没有得到更新
组件代码
import React, { useEffect } from "react"
import { newsComponentService } from "../services/newsComponentService";
const NewsComponent = () => {
const [newsComponentData, setNewsComponentData] = React.useState({});
const componentData = React.useRef("");
async function newsComponentHandler() {
let res = await newsComponentService();
//console.log(res);
setNewsComponentData(res);
//console.log(res);
}
useEffect(() => {
newsComponentHandler();
//setNewsComponentData(res);
}, [setNewsComponentData]);
console.log(newsComponentData["data"]);
return (
<p>{newsComponentData["data"]}</p>
)
}
export default NewsComponent;
api服务代码
export async function newsComponentService(){
const response = await fetch("api/news-categories/1", {
method: 'GET',
headers: {
'Accept': 'application/json',
},
});
let resJson = await response.json();
//console.log(resJson);
return resJson;
}
我认为问题可能与JS的异步行为有关。
import React, { useEffect } from "react"
import { newsComponentService } from "../services/newsComponentService";
const NewsComponent = () => {
const [newsComponentData, setNewsComponentData] = React.useState({});
const componentData = React.useRef("");
useEffect(() => {
const newsComponentHandler = async () => {
let res = await newsComponentService();
setNewsComponentData(res);
}
newsComponentHandler();
}, [setNewsComponentData]);
console.log(newsComponentData["data"]);
return (
<p>{newsComponentData["data"]}</p>
)
}
export default NewsComponent;
p。作为一个好的实践,请将API抓取放在newsComponentService.js