reactjs - React useEffect 获取数据并通过控制台打印出来

我想从 API 获取数据,然后将其打印出来或在我的 react 组件的 return 语句中显示它,这样我就可以拥有一个 p 元素,其中包含从 api 获取的数据。问题是 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;


}

回答1

我认为问题可能出在 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;

PS。作为一个好的做法,请将 API 获取放在 newsComponentService.js 中的 try-catch 块中

相似文章

最新文章