猿问

为什么 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});

}) }


Cats萌萌
浏览 405回答 1
1回答

慕运维8079593

const res =await axios.get('http://localhost:5000/api/albums/all')const {data}= await res;setAlbum({...data,albums:res.data})你能解释一下吗?为什么要等待资源,为什么要传播数据并将其添加为专辑?你可以编写自己的钩子。您还应该fetchApi在 useEffect 钩子中声明该函数,这就是它始终重新渲染的原因。让我们用你的代码做一个自定义的钩子import axios from 'axios';import React, { useEffect, useState } from 'react';function useAlbums() {&nbsp; const [albums, setAlbums] = useState([]);&nbsp; useEffect(() => {&nbsp; &nbsp; const fetchData = async () => {&nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; const { data } = await axios.get(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'http://localhost:5000/api/albums/all',&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; setAlbums(data);&nbsp; &nbsp; &nbsp; &nbsp; console.log(albums);&nbsp; &nbsp; &nbsp; } catch (err) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; fetchData();&nbsp; }, [albums]);&nbsp; return [albums, setAlbums];}const Component = () => {&nbsp; // use it in component&nbsp; const [albums] = useAlbums();&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; {albums.map(({ _id }) => (&nbsp; &nbsp; &nbsp; &nbsp; <div key={_id}>{'add more content here'}</div>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </>&nbsp; );};与const [albums, setAlbums] = useAlbums();希望这可以帮助!
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答