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:
- Without this parameter: Any update to the component, the useEffect is executed with the corresponding return function and function
- Null array: executes only once at componentDidMount, does not listen for updates to component,
- The array has a specific dependency: The corresponding dependency data is executed only when it changes.
0 Comments