我用 create-react-app 创建了一个项目,
我正在尝试 React 钩子(Hook),
在下面的例子中,console.log(articles)
这句话无休止地运行:
import React, {useState, useEffect} from "react"
import {InfiniteScroller} from "react-iscroller";
import axios from "axios";
import './index.less';
function ArticleList() {
const [articles, setArticles] = useState([]);
useEffect(() => {
getArticleList().then(res => {
setArticles(res.data.article_list);
console.log(articles);
});
},[articles]);
const getArticleList = params => {
return axios.get('/api/articles', params).then(res => {
return res.data
}, err => {
return Promise.reject(err);
}).catch((error) => {
return Promise.reject(error);
});
};
let renderCell = (item, index) => {
return (
<li key={index} style={{listStyle: "none"}}>
<div>
<span style={{color: "red"}}>{index}</span>
{item.content}
</div>
{item.image ? <img src={item.image}/> : null}
</li>
);
};
let onEnd = () => {
//...
};
return (
<InfiniteScroller
itemAverageHeight={66}
containerHeight={window.innerHeight}
items={articles}
itemKey="id"
onRenderCell={renderCell}
onEnd={onEnd}
/>
);
}
export default ArticleList;
这是为什么?如何处理?
最佳答案
React useEffect 将第二个参数与其先前的值进行比较,在您的案例中为文章。但是在 javascript 中比较对象的结果总是错误的,尝试在浏览器控制台中比较 [] === [] 你会得到错误的。所以解决方案不是比较整个对象,而是比较articles.lenght
const [articles, setArticles] = useState([]);
useEffect(() => {
getArticleList().then(res => {
setArticles(res.data.article_list);
console.log(articles);
});
},[articles.length]);
关于reactjs - 为什么 React hook useEffect 无休止地运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53976474/