首页 > 解决方案 > 在反应组件中使用 setInterval 重复函数调用的一种替代方法?

问题描述

我有 3 个函数在我的反应组件中重复运行。他们工作正常,但我想清理代码,以便我可以重复调用该函数,而无需初始化然后设置间隔。

有没有办法在没有componentDidMount中的初始函数调用的情况下调用函数并设置间隔?

export class CryptoData extends Component {
    static propTypes = {
    pair: PropTypes.string.isRequired
    }

    state = {
        price: null,
        change1Hr: null,
        change24Hr: null
    }

    getAsync = (func, state) => {
        func(this.props.pair).then(res => {
            this.setState({ [state]: res })
        }).catch(err => console.log(err))
    }

    componentDidMount() {
        this.getAsync(getPrice, "price")
        this.getAsync(get1HrChange, "change1Hr")
        this.getAsync(get24HrChange, "change24Hr") // <- Remove fist 3 lines?
        this.interval = setInterval(() => this.getAsync(getPrice, "price"), 15000)
        this.interval = setInterval(() => this.getAsync(get1HrChange, "change1Hr"), 30000);
        this.interval = setInterval(() => this.getAsync(get24HrChange, "change24Hr"), 20000)
    }
    componentWillUnmount() {
        clearInterval(this.interval);
    }

标签: javascriptreactjs

解决方案


使用钩子,您可以将获取和更新值的所有逻辑抽象到一个钩子中:

 function useUpdatedData(fetcher, interval) {
    const [value, setValue] = useState(null);
    
   useEffect(() => {
     let timer;
     async function update() {
        setValue(await fetcher());
        timer = setTimeout(update, interval); 
      }
      update();
      return () => clearTimeout(timer);
    }, [fetcher]);
  
    return value;
 }

 function CryptoData() {
    const price = useUpdatedData(getPrice, 1500);
    //...
  }

推荐阅读