Reactjs 如何修复递归更新状态?

Reactjs 如何修复递归更新状态?,reactjs,react-lifecycle,Reactjs,React Lifecycle,我正在使用newsapi构建一个应用程序。我在我的国家面临两个问题。我使用api获取数据并将其分配到我的状态。并在我看来使用它 第一期 我的视图在我的应用程序接收数据之前呈现 第二期 当我尝试在新获取后更新状态时。它一次又一次地递归更新数据集 import React, {Component} from 'react'; import NewsComponent from './NewsComponent/NewsComponent' class News extends Component

我正在使用newsapi构建一个应用程序。我在我的国家面临两个问题。我使用api获取数据并将其分配到我的状态。并在我看来使用它

第一期 我的视图在我的应用程序接收数据之前呈现

第二期 当我尝试在新获取后更新状态时。它一次又一次地递归更新数据集

import React, {Component} from 'react';
import NewsComponent from './NewsComponent/NewsComponent'

class News extends Component {
    state = {
        displayStatus: false,
        newsItems: []
    };

    toogleDisplayHandler = () => {
        if(this.state.displayStatus===true){
        this.setState({displayStatus:false})
        }
        else{
        this.setState({displayStatus:true})
        }
    }

    render(){   
        const NewsAPI = require('newsapi');
        const newsapi = new NewsAPI('d6da863f882e4a1a89c5152bd3692fb6');
        //console.log(this.props.keyword);
        newsapi.v2.topHeadlines({
            sources: 'bbc-news,abc-news',
            q: this.props.keyword
        }).then(response => {
            //console.log(response)
            response.articles.map(article => {
                //console.log(article);
                return(
                    //console.log(this.state.newsItems)
                    this.setState({
                        newsItems: [...this.state.newsItems, article],
                    })
                    //this.state.newsItems.push(article)
                                        
                )
            });
        });
    
        let Article = null;    
            
        Article = (
            <div>
                {
                this.state.newsItems.map((news, index) => {
                    return (
                    <NewsComponent key={index}
                        title={news.title}
                        url={news.url}
                        description={news.description}
                        author={news.author}
                        publish={news.publishedAt}
                        image={news.urlToImage}
                    />
                    )
                })
                }
            </div>
        )

    return (
        <div className="App">
        
            {Article}

            <button onClick={this.toogleDisplayHandler}>
                {this.state.displayStatus === true ? "Hide Article" : "Display Articles"}
            </button>
        </div>
        
    )
    }
    
}

export default News;
import React,{Component}来自'React';
从“./NewsComponent/NewsComponent”导入NewsComponent
类新闻扩展组件{
状态={
显示状态:false,
新闻项目:[]
};
toogleDisplayHandler=()=>{
if(this.state.displayStatus==true){
this.setState({displayStatus:false})
}
否则{
this.setState({displayStatus:true})
}
}
render(){
const NewsAPI=require('NewsAPI');
const newsapi=新的newsapi('d6da863f882e4a1a89c5152bd3692fb6');
//console.log(this.props.keyword);
newsapi.v2.topHeaders({
资料来源:“bbc新闻,abc新闻”,
问:this.props.keyword
})。然后(响应=>{
//console.log(响应)
response.articles.map(article=>{
//console.log(文章);
返回(
//console.log(this.state.newsItems)
这是我的国家({
newsItems:[…this.state.newsItems,文章],
})
//this.state.newsItems.push(文章)
)
});
});
让Article=null;
第条=(
{
this.state.newsItems.map((新闻,索引)=>{
返回(
)
})
}
)
返回(
{第条}
{this.state.displayStatus==true?“隐藏文章”:“显示文章”}
)
}
}
导出默认消息;

请帮助我解决此问题。

您不应该在
渲染中
设置状态
,因为这将导致无限循环。在
componentDidMount
构造函数中执行此操作

我还建议不要使用map来简单地迭代列表
Array.map
是一个函数,用于返回通过迭代另一个数组构造的数组。如果要为数组的每个元素运行一些代码,请改用
array.forEach

像这样:

import React, { Component } from "react";
import NewsComponent from "./NewsComponent/NewsComponent";

class News extends Component {
  state = {
    displayStatus: false,
    newsItems: []
  };

  toogleDisplayHandler = () => {
    if (this.state.displayStatus === true) {
      this.setState({ displayStatus: false });
    } else {
      this.setState({ displayStatus: true });
    }
  };

  componentDidMount = () => {
    const NewsAPI = require("newsapi");
    const newsapi = new NewsAPI("d6da863f882e4a1a89c5152bd3692fb6");

    newsapi.v2
      .topHeadlines({
        sources: "bbc-news,abc-news",
        q: this.props.keyword
      })
      .then(response => {
        response.articles.forEach(article => {
          this.setState({
            newsItems: [...this.state.newsItems, article]
          });
        });
      });
  };

  render() {
    let Article = null;

    Article = (
      <div>
        {this.state.newsItems.map((news, index) => {
          return (
            <NewsComponent
              key={index}
              title={news.title}
              url={news.url}
              description={news.description}
              author={news.author}
              publish={news.publishedAt}
              image={news.urlToImage}
            />
          );
        })}
      </div>
    );

    return (
      <div className="App">
        {Article}

        <button onClick={this.toogleDisplayHandler}>
          {this.state.displayStatus === true
            ? "Hide Article"
            : "Display Articles"}
        </button>
      </div>
    );
  }
}

export default News;

import React,{Component}来自“React”;
从“/NewsComponent/NewsComponent”导入NewsComponent;
类新闻扩展组件{
状态={
显示状态:false,
新闻项目:[]
};
toogleDisplayHandler=()=>{
if(this.state.displayStatus===true){
this.setState({displayStatus:false});
}否则{
this.setState({displayStatus:true});
}
};
componentDidMount=()=>{
const NewsAPI=require(“NewsAPI”);
const newsapi=新的newsapi(“d6da863f882e4a1a89c5152bd3692fb6”);
newsapi.v2
.头条新闻({
资料来源:“bbc新闻,abc新闻”,
问:this.props.keyword
})
。然后(响应=>{
response.articles.forEach(article=>{
这是我的国家({
newsItems:[…this.state.newsItems,文章]
});
});
});
};
render(){
让Article=null;
第条=(
{this.state.newsItems.map((新闻,索引)=>{
返回(
);
})}
);
返回(
{第条}
{this.state.displayStatus===true
?“隐藏物品”
:“显示文章”}
);
}
}
导出默认消息;

您不应该在
渲染中
设置状态
,因为这会导致无限循环。在
componentDidMount
构造函数中执行此操作

我还建议不要使用map来简单地迭代列表
Array.map
是一个函数,用于返回通过迭代另一个数组构造的数组。如果要为数组的每个元素运行一些代码,请改用
array.forEach

像这样:

import React, { Component } from "react";
import NewsComponent from "./NewsComponent/NewsComponent";

class News extends Component {
  state = {
    displayStatus: false,
    newsItems: []
  };

  toogleDisplayHandler = () => {
    if (this.state.displayStatus === true) {
      this.setState({ displayStatus: false });
    } else {
      this.setState({ displayStatus: true });
    }
  };

  componentDidMount = () => {
    const NewsAPI = require("newsapi");
    const newsapi = new NewsAPI("d6da863f882e4a1a89c5152bd3692fb6");

    newsapi.v2
      .topHeadlines({
        sources: "bbc-news,abc-news",
        q: this.props.keyword
      })
      .then(response => {
        response.articles.forEach(article => {
          this.setState({
            newsItems: [...this.state.newsItems, article]
          });
        });
      });
  };

  render() {
    let Article = null;

    Article = (
      <div>
        {this.state.newsItems.map((news, index) => {
          return (
            <NewsComponent
              key={index}
              title={news.title}
              url={news.url}
              description={news.description}
              author={news.author}
              publish={news.publishedAt}
              image={news.urlToImage}
            />
          );
        })}
      </div>
    );

    return (
      <div className="App">
        {Article}

        <button onClick={this.toogleDisplayHandler}>
          {this.state.displayStatus === true
            ? "Hide Article"
            : "Display Articles"}
        </button>
      </div>
    );
  }
}

export default News;

import React,{Component}来自“React”;
从“/NewsComponent/NewsComponent”导入NewsComponent;
类新闻扩展组件{
状态={
显示状态:false,
新闻项目:[]
};
toogleDisplayHandler=()=>{
if(this.state.displayStatus===true){
this.setState({displayStatus:false});
}否则{
this.setState({displayStatus:true});
}
};
componentDidMount=()=>{
const NewsAPI=require(“NewsAPI”);
const newsapi=新的newsapi(“d6da863f882e4a1a89c5152bd3692fb6”);
newsapi.v2
.头条新闻({
资料来源:“bbc新闻,abc新闻”,
问:this.props.keyword
})
。然后(响应=>{
response.articles.forEach(article=>{
这是我的国家({
newsItems:[…this.state.newsItems,文章]
});
});
});
};
render(){
让Article=null;
第条=(
{this.state.newsItems.map((新闻,索引)=>{
返回(
);
})}
);
返回(
{第条}
{this.state.displayStatus===true
?“隐藏物品”
:“显示文章”}
);
}
}
导出默认消息;
1)您可以添加一项检查,检查您的状态是否有要在屏幕上显示的数据,以呈现视图

2) 请使用ComponentDidMountReact生命周期函数从外部源获取数据,并在状态中更新此数据。在Render方法中,它将继续递归调用它

1)你可以做广告