ReactJS: how to call useEffect hook only once to fetch API data

后端 未结 2 800
野的像风
野的像风 2020-12-18 21:59

Using React, I have the following functional component where I make use of useEffect():

import React, { useEffect } from \'react\';
import { con         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 22:39

    If I understand correctly, you want to mimic the "on component mounted" behaviour of regular class based react components via useEffect(), so that the effect callback only fires once on the first render.

    To achieve that behaviour, you can pass an empty array to the second argument of useEffect() like so:

    useEffect(() => {
      loadMessages();
    }, []); /* <-- add this */
    

    The second array argument allows you to specify which prop variables trigger the userEffect() callback (if any) when their value(s) change.

    By passing an empty array, this means that useEffect() won't be triggered by any changes to input prop variables and will in turn only ever be called once, during the first render.

    For more information on this second argument, see this documentation and this documentation

提交回复
热议问题