简体   繁体   English

(反应)当我从 API 获取一些数据时,如何阻止我的 web 应用程序重新渲染?

[英](React) How can I stop my web app from re-rendering when I fetch some data from an API?

I made a web app that fetches and displays information about random countries using the REST countries API ( https://restcountries.eu/ ). I made a web app that fetches and displays information about random countries using the REST countries API ( https://restcountries.eu/ ). Something that bugs me and I don't understand why it happens (I've been running over and over the code and I don't see the problem) is that when I press the "New Country" button, I see that it displays briefly a country, and then re-renders the App, and brings another country.让我烦恼并且我不明白为什么会发生的事情(我一直在反复运行代码并且我没有看到问题)是当我按下“新国家”按钮时,我看到它显示简述一个国家,然后重新渲染App,并带上另一个国家。 It's more of a nuisance, but I'd like to get it fixed because it's not very smooth.这更令人讨厌,但我想修复它,因为它不是很顺利。 Thoughts?想法? Thank you!谢谢!

import React, {useState, useEffect} from "react"

function CountryInfo() {
    const [loading, setLoading] = useState(true)
    const [countryName, setCountryName] = useState("")
    const [countryCapital, setCountryCapital] = useState("")
    const [countryPopulation, setCountryPopulation] = useState(0)
    const [countryRegion, setCountryRegion] = useState("")
    const [countrySubRegion, setCountrySubRegion] = useState("")
    const [countryArea, setCountryArea] = useState(0)
    const [countryFlag, setCountryFlag] = useState("")
    

    function fetchData() {
        fetch("https://restcountries.eu/rest/v2/all")
            .then(response => response.json())
            .then(data => {
                var randomCountry = Math.floor(Math.random() * (data.length - 1) + 1)
                setLoading(false)
                setCountryName(data[randomCountry].name)
                setCountryCapital(data[randomCountry].capital)
                setCountryPopulation(data[randomCountry].population)
                setCountryArea(data[randomCountry].area)
                setCountryRegion(data[randomCountry].region)
                setCountrySubRegion(data[randomCountry].subregion)
                setCountryFlag(data[randomCountry].flag)
            })
    }

    useEffect(() => {
        fetchData()
    }, [])

    return (
        <div className="country-info">
            <div style={{display: loading? 'block' : 'none'}}><p>Loading...Please wait</p></div>
            <div style={{display: loading? 'none' : 'block'}}>
                <h1>Random Country: {countryName}</h1>
                <hr />
                <p>Let's get some facts!</p>
                <p>Capital: {countryCapital}</p>
                <p>Population: {countryPopulation}</p>
                <p>Region: {countryRegion}</p>
                <p>Sub-region: {countrySubRegion}</p>
                <p>Area: {countryArea} km</p>
            </div>
            <img src={countryFlag}></img>
            <form onSubmit={fetchData}><button>New Country</button></form>
        </div>
    )
}

export default CountryInfo

In order to render your component correctly and catch an error whenever something happens during the call to your api, avoid using the boolean type for the loading and use string to describe the status.为了正确呈现您的组件并在调用 api 期间发生任何事情时捕获错误,请避免使用 boolean 类型进行加载并使用字符串来描述状态。 I did some modification in your code:我对你的代码做了一些修改:

import React, {useState, useEffect} from "react"

function CountryInfo() {
    const [loading, setLoading] = useState('idle');
    const [error, setError] = useState('');

    const [country, setCountry] = useState({
      name: '',
      capital: '',
      population: 0,
      region: '',
      subregion: '',
      area: 0,
      flag: ''
    })
    

    function fetchData() {
        setLoading('pending');
        fetch("https://restcountries.eu/rest/v2/all")
            .then(response => response.json())
            .then(data => {
                var randomCountry = Math.floor(Math.random() * (data.length - 1) + 1)
                setCountry(data[randomCountry]);
                setLoading('resolved')
            })
            .catch((error) => {
              setLoading('rejected');
              setError(error);
            })
    }

    useEffect(() => {
        fetchData()
    }, [])

    let content;
    if (loading === 'pending' || loading === 'idle') {
      content = <h1>...Loading</h1>
    } else if (loading === 'rejected') {
      content = <div>
      <div>Oops an error occured:</div>
      <pre>{error.message}</pre>
      </div>
    } else {
      content = (
        <div className="country-info">
            <div style={{display: 'block'}}>
                <h1>Random Country: {country.name}</h1>
                <hr />
                <p>Let's get some facts!</p>
                <p>Capital: {country.capital}</p>
                <p>Population: {country.population}</p>
                <p>Region: {country.region}</p>
                <p>Sub-region: {country.subregion}</p>
                <p>Area: {country.area} km</p>
            </div>
            <img alt='countryFlag' src={country.flag}></img>
            <form onSubmit={fetchData}><button>New Country</button></form>
        </div>
    )
    }

    return content;
}

export default CountryInfo;

For further information check this link Stop using isLoading booleans有关更多信息,请查看此链接Stop using isLoading booleans

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我更改语言时,如何阻止我的 React 应用程序重新呈现? - How can I stop my React app from re-rendering when I change language? 如何防止我的功能组件使用 React 备忘录或 React 钩子重新渲染? - How can I prevent my functional component from re-rendering with React memo or React hooks? 如何在父组件重新加载时阻止子组件重新渲染 - How do I stop a child component from re-rendering when its parent reloads React 和 Chartjs:重新渲染时如何最好地销毁图表? - React & Chartjs: How can I best destroy my chart when re-rendering? react-native:如何阻止制表符重新渲染? - react-native: How to stop tab from re-rendering? 更改路由时如何防止 React 组件重新渲染? - How to prevent React component from re-rendering when I am changing routes? 更新Redux存储时,React不重新渲染 - React not re-rendering when I update my redux store 当 class 从道具获取新数据时,如何触发重新渲染? - How do I trigger re-rendering when a class gets new data from a prop? 当我更改 state 时,为什么我的 React 应用程序没有重新渲染? - Why isn't my React app re-rendering when I change the state? 我使用 React hooks 和 React memo 来防止我的功能组件重新渲染,但不起作用? - I use React hooks and React memo to prevent my functional component from re-rendering ,but not work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM