简体   繁体   English

如何在 React function 组件中不使用 useEffect 钩子来获取数据?

[英]How to fetch data without useEffect hooks in React function component?

I know the conventional way when using hooks is to fetch the data using the useEffect hook.我知道使用挂钩的传统方法是使用useEffect挂钩获取数据。 But why can't I just call axios in the functional component instead of a hook and then set the data.但是为什么我不能直接在功能组件中调用axios而不是一个hook然后设置数据呢。

Basically, I am asking what is wrong with doing this:基本上,我问这样做有什么问题:

const [users, setUsers] = useState(null);
axios.get("some api call")
  .then(res => setUsers(res.data))

Here, I do not use useEffect , what could go wrong?在这里,我没有使用useEffect , go有什么错?

Making a request and changing the state on render like that will cause the component to re-render forever.发出请求并在渲染时更改 state 将导致组件永远重新渲染。

Every time the component renders, eg due to props changing or due to hooks changing , that axios.get request gets called.每次组件呈现时,例如由于 props 更改或由于挂钩更改,都会调用axios.get请求。 When it gets a response, it will update the state. Then, because the state has changed, the component re-renders, and axios.get is called again.当它得到响应时,它会更新 state。然后,因为 state 已经改变,组件重新渲染,并再次调用axios.get And the state changes again, and the request is made again, forever.而 state 再次发生变化,并且永远再次发出请求。

Prefer useEffect(() => code... , []) .更喜欢useEffect(() => code... , [])

That said, you can also do it while avoiding an infinite loop but it's a very bad practice and I don't recommend it.也就是说,您也可以在避免无限循环的同时做到这一点,但这是一种非常糟糕的做法,我不推荐这样做。

Yes, you will have a re-render but you won't have an infinite loop.是的,您将进行重新渲染,但不会出现无限循环。 Use useState's lazy init function .使用useState 的惰性初始化 function

const [users, getUsers] = useState(() => {
   axios.get("some api call")
     .then(res => getUsers(res.data))
});

Best practice is:最佳做法是:

const [users,getUsers]= useState();
useEffect ( () => {
   axios.get("some api call")
  .then(res=>getUsers(res.data))
}, []);

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

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