使用 settimeout 和 setstate 在 React 中消除抖动

问题描述 投票:0回答:1

这个代码可以接受吗?我已经测试过它并且有效,但我不知道这是否是一个好的做法。基本上,每当有人在输入中输入内容时,我都会调用数据。但 API 调用太多了。所以我做了所谓的“去抖动”,这样当他们停止输入时就会进行 API 调用。

我想更简单的方法是有一个按钮,这样他们按下它就可以拨打一个电话。但我正在尝试输入

onchange
方法。

class Weather extends React.Component{
state={
    data:[],
    target:'',
    timer:null
}
componentDidMount(){
    this.setState({timer:null})
}
handleChange=(e)=>{
    this.setState({
        target: e.target.value
    })
    clearTimeout(this.state.timer);
    this.setState({timer:setTimeout(()=>{
        this.fetch_geocodes()
    },2000)})
}
javascript reactjs asynchronous settimeout debouncing
1个回答
0
投票

如果您有充分的理由使用类组件,那么在类组件中使用去抖动并没有什么问题。如果我正在写那门课,我会做出这些改进:

  • 使用构造函数来初始化类属性,因为这是更好的做法。
  • 在状态之外启动定时器,无需用定时器污染状态。
  • 无需在代码中调用 componentDidMount() 函数。

经过上述更改,新类将如下所示:

class Weather extends React.Component{
  constructor() {
    this.state = {
      data:[],
      target:'',
    };

    this.timer = null;
 }

  handleChange=(e)=>{
    this.setState({target: e.target.value})
    clearTimeout(this.timer); //if handlechange is called within 2 seconds again then clear timeout and the previous call to fetch_geocodes in wait will not execute
    this.timer = setTimeout(this.fetch_geocodes, 2000) // call fetch_geocodes after 2 seconds of wait
   }
}

如果您没有充分的理由使用类组件,则使用功能组件,并考虑查看本教程在功能组件中实现去抖动

© www.soinside.com 2019 - 2024. All rights reserved.