Today I tried to get data from the back end by calling a GET request, and then saved it to the state. But it caused an endless loop that kept sending requests. The code is as follows

const [article, setArticle] = useState();

axios.get(url).then(({data}) => {
    setArticle(data)
})
 

Solution: Use useEffect to replace lifecycle function.

const [article, setArticle] = useState();

useEffect(() => {
    axios.get(url).then(({data}) => {
        setArticle(data)
    })
},[]) 

useEffect: Side effect hook, used to deal with side effects in components, used to replace lifecycle functions.The so-called “side effect” refers to the component state or life cycle change can be monitored in useEffect.

 

useEffect can be used in several ways, depending on the second parameter:

  1. Without this parameter: Any update to the component, the useEffect is executed with the corresponding return function and function
  2. Null array: executes only once at componentDidMount, does not listen for updates to component,
  3. The array has a specific dependency: The corresponding dependency data is executed only when it changes.

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *