[英]Where should we make an API request in React?
I have always made API's
request in ComponentDidMount
lifecycle and called setState
in the callback.我一直在
ComponentDidMount
生命周期中发出API's
请求,并在回调中调用setState
。 But while digging deep I happened to find out We should not call setState in this lifecycle as it triggers render method again and React also doesn't recommend that.但是在深入挖掘的过程中,我偶然发现我们不应该在这个生命周期中调用 setState ,因为它会再次触发 render 方法,而 React 也不建议这样做。
Then in that case where exactly we should make that request and call setState
to use result after that?那么在这种情况下,我们到底应该在哪里发出请求并调用
setState
来使用结果呢?
You should absolutely make an API call in componentDidMount
.您绝对应该在
componentDidMount
进行 API 调用。 What is not recommended is to re-render a big component, instead what you should do is break your UI into small logical components and only re-render only what is needed , not a whole.不推荐的是重新渲染一个大的组件,而是你应该做的是将你的 UI 分解成小的逻辑组件,只重新渲染需要的部分,而不是整体。 For example, you have a big component named
HomeComponent
which has 3 small components called NavComponent
, BodyComponent
and FooterComponent
.例如,你有一个很大的命名组件
HomeComponent
其中有3个个小的元件称为NavComponent
, BodyComponent
和FooterComponent
。 You should NOT be calling the API from the componentDidMount
of the HomeComponent
since calling setState
from HomeComponent
will re-render all the small components inside HomeComponent
, which is not necessary since you know that the navbar or footer is not needed to be re-rendered.你不应该调用从该API
componentDidMount
中的HomeComponent
因为调用setState
从HomeComponent
将重新呈现内所有的小部件HomeComponent
,因为你知道,在导航栏或页脚是不是需要重新渲染这是没有必要的。 Rather from the BodyComponent
, because only the body part needs to be re-rendered since its state has changed.而不是来自
BodyComponent
,因为只有身体部分需要重新渲染,因为它的状态已经改变。 So you should be calling the API from the componentDidMount
of the BodyComponent
, that way you re-render only whats needed.所以你应该从
BodyComponent
的componentDidMount
调用 API,这样你就只重新渲染需要的东西。
@Shababb Karim is right but if i were to implement API calls in my project i would add a state management library. @Shababb Karim 是对的,但如果我要在我的项目中实现 API 调用,我会添加一个状态管理库。 Redux is a great way to implement a global state to the app where you can set data from said API.
Redux 是一种向应用程序实现全局状态的好方法,您可以在其中设置来自所述 API 的数据。 All components that need that data can be attached to the Redux state to get it.
所有需要该数据的组件都可以附加到 Redux 状态以获取它。
Redux can be a bit of overhead in smaller projects though.不过,在较小的项目中,Redux 可能会带来一些开销。 In this case there are other options like Flux (although i like Redux more).
在这种情况下,还有其他选项,如 Flux(虽然我更喜欢 Redux)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.