javascript - 为什么每次渲染后都会执行useEffect?
问题描述
我的效果挂钩有问题。我只希望它渲染一次。如果我传递 album.length 或一个空数组,它会返回一个空对象。如果将专辑作为依赖项添加,则效果将呈现为无限循环。任何帮助表示赞赏。
const [album, setAlbum] = React.useState(initialState)
const {state} = React.useContext(AuthContext);
async function fetchData(){
try{
const res =await axios.get('http://localhost:5000/api/albums/all')
const {data}= await res;
setAlbum({...data,albums:res.data})
console.log(album)
}
catch(err){
console.log(err);
}
}
useEffect(() => {fetchData();}, []);
_______________________________________________________
componentDidMount(){
axios.get('http://localhost:5000/api/albums/all')
.then(res=>{
let albums=res.data.map((album)=>{
return(
<div key={album._id}>
//display the album
</div>
</div>
</div>
)
})
this.setState({albums:albums});
}) }
解决方案
const res =await axios.get('http://localhost:5000/api/albums/all')
const {data}= await res;
setAlbum({...data,albums:res.data})
Can you please explain this? Why await res and why spread data and add it as albums as well?
You could write your own hook. You should also declare the function fetchApi
within the useEffect hook, that is why it re-renders the whole time.
Let's take your code and make a custom hook
import axios from 'axios';
import React, { useEffect, useState } from 'react';
function useAlbums() {
const [albums, setAlbums] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const { data } = await axios.get(
'http://localhost:5000/api/albums/all',
);
setAlbums(data);
console.log(albums);
} catch (err) {
console.log(err);
}
};
fetchData();
}, [albums]);
return [albums, setAlbums];
}
const Component = () => {
// use it in component
const [albums] = useAlbums();
return (
<>
{albums.map(({ _id }) => (
<div key={_id}>{'add more content here'}</div>
))}
</>
);
};
Use with
const [albums, setAlbums] = useAlbums();
Hope this helps!
推荐阅读
- node.js - 向 Node Web 服务器的每个请求发送有效的 JWT 令牌时出现禁止 403 http 错误
- javascript - 执行功能后如何显示组件?
- react-navigation - 直接导航到 StackNavigator 的底部屏幕,同时为中间屏幕提供参数
- javascript - index.js 的单元测试功能
- oracle - 在不满足条件的情况下获取所有记录
- javascript - Mapbox 使用哪个投影
- java - 如何在向亚马逊 MWS 提交 Feed 时修复“格式错误的 xml”错误?
- php - 在 Symfony 中反序列化 JSON 响应
- puppeteer - Puppeteer:如何将默认浏览器上下文设置为隐身模式?
- javascript - 如何创建动态 HTTP 请求路径