【问题标题】:API giving data in second render in ReactAPI 在 React 的第二次渲染中提供数据
【发布时间】:2021-02-26 16:42:54
【问题描述】:

我试图用 react.js 获取 api,但在第一次渲染时它没有给出任何东西,而第二次渲染它给出了数据。这使得当我稍后尝试访问图像的数据时出现错误,TypeError: Cannot read property 'news.article' of undefined,因为它最初是空的。我该如何解决?

这是我的代码..

import React, { useEffect, useState } from 'react';

const HomeContent = () => {
    const [news, updateNews] = useState([]);
    console.log(news);
    useEffect(() => {
        const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
        fetch(api)
            .then(response => response.json())
            .then(data => updateNews(data))
            .catch((error) => console.log(error))
    }, [])

    return (
        <>

        </>
    );
};

export default HomeContent;

【问题讨论】:

  • 你不需要“解决”它。这就是它应该如何工作的方式。
  • 这使得当我稍后尝试访问图像的数据时出现错误,TypeError: Cannot read property 'news.articles' of undefined, 因为它最初是空的。
  • 重新编辑:在您与我们共享的代码中,您绝不会尝试读取news 的任何属性(更不用说news.articles,这样代码就不会产生该错误。 (如果news 将获得一个名为articles 的属性,那么将它初始化为一个空的array 是没有意义的)。
  • 通常你会有一个额外的loading 状态,当请求完成时你设置为false。然后你可以渲染某种加载指示器,而loading 仍然是true。对于更复杂的应用程序,您还需要一些状态来在获取数据时处理错误。
  • 可以给我一个代码示例吗? @trixn

标签: javascript reactjs api fetch


【解决方案1】:

代码本身没有问题,您收到的输出是预期的。但是,您可以在检索到内容后呈现内容

import React, { useEffect, useState } from 'react';

const HomeContent = () => {
    const [news, updateNews] = useState([]);
    const [isLoading, setIsLoading] = useState(true);    

    console.log(news);
    useEffect(() => {
        const api = 'http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=940c56bd75da495592edd812cce82149'
        fetch(api)
            .then(response => response.json())
            .then(data => { 
                updateNews(data.articles);
                setIsLoading(false);
            })
            .catch((error) => {
               console.log(error);
               setIsLoading(false);
            })
    }, [])

    return (
        <>
            {isLoading ? 
                <p>Loading...</p> :
                // Some JSX rendering the data
            }
        </>
    );
};

export default HomeContent;

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2019-10-06
    • 2023-01-14
    相关资源
    最近更新 更多