简体   繁体   English

react.js中useEffect中的无限获取数据

[英]infinite fetch data in useEffect in react.js

Hi I'm trying to fetch data using personally built axios function named fetchMerchant .嗨,我正在尝试使用名为fetchMerchant的个人构建的 axios function 来获取数据。

I give dependencies in useEffect hook with fullData but it seems infinite looping after render and re render.我在 useEffect 钩子中使用fullData提供依赖项,但在渲染和重新渲染后似乎无限循环。

In my opinion, It should be rendered once after useEffect hooks because of dependency fullData given as a array.在我看来,它应该在 useEffect 钩子之后渲染一次,因为依赖fullData作为数组给出。

How can I prevent infinite rendering after useEffect? useEffect 后如何防止无限渲染?


  const BoardPage: FC =() => {
  const [fullData, setData] = useState<ContentType>({} as ContentType);
  const fetchData = async() => {
    try{
      const [,response] = await fetchMerchant();
      console.log(response);
      setData(response);
    } catch(error){
      console.log(error);
    }
  }
  useEffect(() => {
    console.log("board rendered");

    fetchData();
  },[fullData]) 
  return(
    <>
      <Board data={fullData} /> 
    </> 
  )
};

It's running infinitely because of how your hook is setup.由于你的钩子是如何设置的,它会无限运行。 When you place something in the brackets at the end of the hook [fullData] it means that the hook will fire when that value changes.当您在钩子[fullData]末尾的括号中放置一些内容时,这意味着该钩子将在该值更改时触发。 You don't want that to happen in this case because fetchData() inside of the hook will cause fullData to change thus firing the hook again.在这种情况下,您不希望这种情况发生,因为钩子内部的fetchData()会导致fullData发生变化,从而再次触发钩子。 If you leave the brackets empty like so it should only fire once when the component is mounted如果您将括号留空,那么它应该只在安装组件时触发一次

  useEffect(() => {
    console.log("board rendered");

    fetchData();
  },[])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM