【问题标题】:How can we stop repeated calls in componentDidUpdate() lifecycle of a class based component, like we do in useEffect hook?我们如何在基于类的组件的 componentDidUpdate() 生命周期中停止重复调用,就像我们在 useEffect 挂钩中所做的那样?
【发布时间】:2020-08-26 05:36:35
【问题描述】:
使用效果(()=>{ 获取(`${BASE_URL}/requested_url`) .then(响应 => response.json()) .then(json => setData(json)) }, []);

当我使用基于类的组件时,我必须使用状态布尔值来指定何时开始获取和停止......我试图完成工作很奇怪,但我仍然很想知道我们是否可以停止在 componentDidUpdate() 生命周期方法中也重复调用请求。

组件DidUpdate() { 如果(this.state.show2){ 返回获取(`${BASE_URL}/requested_url`) .then(响应 => response.json()) .then(json => setState({ 数据:json, 显示2:假 })) } 返回; }

我知道这不是从生命周期进行请求调用的正确方法。也不要因此评判我......所以,请告诉我是否有人可以帮助我正确地做到这一点,或者这样做是否合法......

【问题讨论】:

  • componentDidUpdate(prevProps, prevState) {} - 你可以使用 prevState 参数,确定状态是否改变。例如 if (prevState.show2 !== this.state.show2) {// 提出您的请求}
  • 你应该创造一些条件来满足你的要求

标签: reactjs react-functional-component react-lifecycle react-lifecycle-hooks react-class-based-component


【解决方案1】:

useEffect 中的第二个属性是一个依赖数组。基本上,效果中使用的任何外部变量都需要放入其中,因为该函数只会在它们更改值时运行。

  useEffect(()=>{
    if (show2)
      fetch(`${BASE_URL}/requested_url`)
        .then(response => response.json())
        .then(json => setData(json))
  }, [show2]);

【讨论】:

  • 我们不能在基于类的组件中使用 Hook 对吧?正如 QA 所提到的,他希望将其存档在基于类的组件中。
猜你喜欢
  • 2011-09-13
  • 1970-01-01
  • 2021-08-21
  • 2017-09-12
  • 2012-03-13
  • 2021-10-15
  • 2021-09-02
  • 2019-05-01
  • 1970-01-01
相关资源
最近更新 更多