返回

点石成金:重构微信小程序倒计时组件

前端

引言

在过去的几个月中,我有幸与一些非常棒的工程师合作,他们帮助我理解了软件工程的真正意义。

其中一位工程师告诉我,好的代码不是写出来的,而是重构出来的。这句话深深地触动了我,也让我意识到代码重构的重要性。

正因如此,我决定重构之前实现的微信小程序倒计时组件。

原始代码分析

回顾之前编写的倒计时组件,我发现了一些问题:

  • 代码可读性差:代码结构混乱,缺乏注释,很难理解和维护。
  • 代码可扩展性差:组件的功能有限,难以扩展。
  • 代码性能差:组件的性能不佳,在某些情况下会导致小程序卡顿。

重构步骤

为了解决这些问题,我按照以下步骤对组件进行了重构:

  1. 重新设计了组件的架构,使其更加模块化和易于理解。
  2. 添加了注释,使代码更容易理解和维护。
  3. 重写了组件的逻辑,使其更加高效和健壮。
  4. 对组件进行了单元测试,以确保其正确性和可靠性。

重构后的代码

经过重构,组件的代码变得更加清晰和易读,同时性能也得到了大幅提升。

以下是重构后的代码:

// 导入必要的模块
import { Component } from '@tarojs/taro';
import './index.scss';

// 定义组件类
class Countdown extends Component {

  // 定义组件的属性
  static propTypes = {
    initDuration: PropTypes.number.isRequired,
    format: PropTypes.string.isRequired,
    onFinish: PropTypes.func
  }

  // 定义组件的默认属性
  static defaultProps = {
    initDuration: 0,
    format: 'hh:mm:ss',
    onFinish: () => {}
  }

  // 定义组件的状态
  state = {
    duration: this.props.initDuration,
    timer: null
  }

  // 组件挂载时执行
  componentDidMount() {
    this.startTimer();
  }

  // 组件卸载时执行
  componentWillUnmount() {
    this.stopTimer();
  }

  // 启动倒计时
  startTimer() {
    this.timer = setInterval(() => {
      if (this.state.duration <= 0) {
        this.stopTimer();
        this.props.onFinish();
        return;
      }

      this.setState({
        duration: this.state.duration - 1
      })
    }, 1000);
  }

  // 停止倒计时
  stopTimer() {
    clearInterval(this.timer);
    this.timer = null;
  }

  // 格式化倒计时时间
  formatDuration(duration) {
    let hours = Math.floor(duration / 3600);
    let minutes = Math.floor((duration % 3600) / 60);
    let seconds = duration % 60;

    if (hours < 10) {
      hours = '0' + hours;
    }

    if (minutes < 10) {
      minutes = '0' + minutes;
    }

    if (seconds < 10) {
      seconds = '0' + seconds;
    }

    return this.props.format.replace('hh', hours).replace('mm', minutes).replace('ss', seconds);
  }

  // 渲染组件
  render() {
    return (
      <View className='countdown'>
        {this.formatDuration(this.state.duration)}
      </View>
    )
  }
}

export default Countdown;

总结

通过重构,组件的代码变得更加清晰和易读,同时性能也得到了大幅提升。

我也从这次重构中吸取了一些经验教训:

  • 代码重构是一个循序渐进的过程,需要耐心和细心。
  • 重构时要考虑代码的可读性、可维护性、可扩展性和性能。
  • 重构时要对组件进行单元测试,以确保其正确性和可靠性。

我希望这篇文章对大家有所帮助。如果您有任何问题或建议,请随时留言。