在 React 中获取连续调用

Fetch in React making call continuosly

我正在从 json 文件中获取数据,但问题是当我检查网络选项卡时。不断有人打电话给我,我该怎么做才能解决这个问题。 : Network Tab Image

class Banner extends Component {

    constructor(props) {
        super(props);
        this.state = {
          buttonLink:"",
          bannerImg:""
        };
    }


    render() {


        const a =  fetch("./logo.json").then(response => response.json())
        .then((temp1)=> {this.setState({buttonLink:temp1.buttonLink,bannerImg:temp1.bannerImg});  
    });
   
return(....
<img src={this.state.bannerImg}></img>
....
)

在 class 组件中,您可以使用一些生命周期方法,例如 componentDidMount 因此,将您的 fetch 方法放在 componentDidMount 中而不是在 render 方法中,因为每当您调用 setState() 方法时,它都会再次调用 render 方法,并且在您的 render 方法中您再次调用 api 和 setState,这会产生无限循环,做这样的事情:

 componentDidMount(){
   const a = fetch("./logo.json").then(response => response.json())
  .then((temp1)=> {this.setState({buttonLink:temp1.buttonLink,bannerImg:temp1.bannerImg});  
 }

您不能在 render 函数中调用 fetch。

您可以使用功能组件轻松获取数据。

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

const Banner = () => {
    const [image, setImage] = useState({ buttonLink: '', bannerImg: '' });

    useEffect(() => {
        fetch('./logo.json')
            .then((response) => response.json())
            .then((temp1) => {
                setImage({ buttonLink: temp1.buttonLink, bannerImg: temp1.bannerImg });
            });
    }, []);

    return <img src={image.bannerImg}></img>;
};

export default Banner;