反应UseState钩子导致无限循环

时间:2019-11-30 03:03:05

标签: reactjs react-hooks

我正在使用ReactJs每5秒抓取一个RSS新闻提要,将其转换为JSON字符串以在网页上呈现。我同时使用useEffect和useState挂钩,因为我在useState挂钩变量中传递了JSON字符串。虽然可以,但是会产生无限循环。我已经搜索了堆栈溢出中提供的修复程序,但是找不到确切的问题。这是我的代码段。'

import React, {useEffect, useState} from 'react';
import Carousel from 'react-bootstrap/Carousel';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {getNews} from "../../actions/news";
import Parser from 'rss-parser';

const NewsCarousel = ({getNews, news: {news, loading} }) => {

    const [getFeed, setFeed] = useState({
        feed: ''
    });

    useEffect(() => {
        const interval = setInterval(() => {
            getNews();
        }, 5000);
        return () => clearInterval(interval);
    }, [getNews]);


    const { feed } = getFeed;
    const newsFeed = feed => setFeed({ ...getFeed, feed: feed });

    let parser = new Parser();
    parser.parseString(news, function(err, feed){
        if (!err) {
            newsFeed(feed);
        } else {
            console.log(err);
        }

    });

    console.log(feed);
    return (
        <div className="dark-overlay">
        </div>
    );
};


NewsCarousel.propTypes = {
    getNews: PropTypes.func.isRequired,
    news: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    news: state.news
});

export default connect(mapStateToProps, {getNews}) (NewsCarousel);

当我在console.log中输入feed变量时,即在控制台中看到无限日志时。 以下是我的getNews动作

import axios from 'axios';
import { GET_NEWS, NEWS_FAIL } from "./types";

export const getNews = () => async dispatch => {
  try{
     const res = await axios.get('https://www.cbc.ca/cmlink/rss- 
     topstories');
     dispatch({
        type: GET_NEWS,
        payload: res.data
     })
} catch(err) {
    dispatch({
        type: NEWS_FAIL,
        payload: { msg: err}
    })
}
};

1 个答案:

答案 0 :(得分:1)

仅当新道具发生变化时,您才需要解析新闻。添加具有新闻作为依赖项的另一个useEffect,以便在新闻更改时将其调用,然后在那里更新您的状态。

import React, {useEffect, useState} from 'react';
import Carousel from 'react-bootstrap/Carousel';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {getNews} from "../../actions/news";
import Parser from 'rss-parser';

const NewsCarousel = ({getNews, news: {news, loading} }) => {

    const [getFeed, setFeed] = useState({
        feed: ''
    });

    useEffect(() => {
        const interval = setInterval(() => {
            getNews();
        }, 5000);
        return () => clearInterval(interval);
    }, [getNews]);

    useEffect(() => {
      const newsFeed = feed => setFeed({ ...getFeed, feed: feed });

      const parser = new Parser();
      parser.parseString(news, function(err, feed){
        if (!err) {
            newsFeed(feed);
        } else {
            console.log(err);
        }
      });
    }, [news]);

    return (
        <div className="dark-overlay">
        </div>
    );
};


NewsCarousel.propTypes = {
    getNews: PropTypes.func.isRequired,
    news: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    news: state.news
});

export default connect(mapStateToProps, {getNews}) (NewsCarousel);