首页 > 解决方案 > 为什么每次渲染后都会执行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});

}) }

标签: javascriptreactjsreact-hooks

解决方案


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!


推荐阅读