【发布时间】:2019-04-08 18:47:17
【问题描述】:
在基于类的组件中:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
this.setState({
posts: res.data.slice(0, 10)
});
console.log(posts);
})
}
我试过这个:
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
setPosts(res.data.slice(0, 10));
console.log(posts);
})
});
它创建了一个无限循环。如果我将 []/{} 作为第二个参数 [1][2] 传递,那么它会阻止进一步的调用。但它也阻止了数组更新。
[2]How to call loading function with React useEffect only once
【问题讨论】:
-
“如果我将
[]/{}作为第二个参数传递,那么它会阻止进一步调用”是什么意思。这就是你想要做的,只在初始渲染后运行给useEffect的函数。 -
是的。我想运行一次该函数,因为它一次又一次地更新帖子数组。遵循您在其他帖子中提到的方法后,我得到了预期的“运行 useEffect 一次”,但我的帖子数组仍然是空的。不应该是 [post1, post2, ...]。
-
@Tholle 我接受了你的回答。
标签: reactjs axios react-hooks