React UseState 钩子导致无限循环



我正在使用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);

当我控制台时.log我的提要变量就是我在控制台中看到无限日志的时候。 以下是我的新闻行动

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}
})
}
};

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

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);

相关内容

  • 没有找到相关文章

最新更新