首页 > 解决方案 > 在 componentDidMount 中调用函数反应原生

问题描述

我试图在安装组件时调用一个函数,这个函数控制一些状态操作。我不确定我做得对。我希望计时器在达到 20 时重新启动,因为没有按钮,我假设它应该在 componentDidMount 中完成。有人可以指出我正确的方向。下面是我想要实现的精简示例代码。

        constructor(props) {
          super(props);
          this.state = { 
            timer: 10,
            timesup: false,
            timing: true,
            showWelcome: true, 
            };
        }

        componentDidMount() {
          this.endTimer();
        this.clockCall = setInterval(() => {
          this.decrementClock();
        }, 1000);
        }

        endTimer = () => {
          if (this.state.timer <= 25) {
                this.setState({
                  timing: true,
                  timer: 30,
                  showWelcome: true,
                  timesup: false,
                })
          }

        }


        decrementClock = () => {  
          this.setState((prevstate) => ({ 
            timer: prevstate.timer-1 
          }), () => {
            if(this.state.timer === 0) {
              clearInterval(this.clockCall)
              this.setState({
                timesup: true,
                timing: false,
                showWelcome: false,
              })
            }
          })
        }


        componentWillUnmount() {
        clearInterval(this.clockCall);
        }


        render() {
          return (
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>

        {this.state.timesup && (
            <Text style={{fontSize: 18, color: '#000'}}>
            Time up
            </Text>)}


        {this.state.timing && (
            <Text style={{fontSize: 18, color: '#000'}}>
            {this.state.timer}
            </Text>)}

              {this.state.showWelcome && (
                <Text style={{ fontSize: 20 }}>Welcome</Text>
              )}
            </View> 
          )
        }
        }

标签: javascriptreactjsreact-native

解决方案


我希望计时器在达到 20 时重新启动,因为没有按钮,我假设它应该在componentDidMount中完成。

不,您需要使用componentDidUpdate生命周期方法来检查timer的当前值。componentDidMount在安装阶段只调用一次。

所以,this.endTimer();componentDidMount.

  componentDidMount() {
    this.clockCall = setInterval(() => {
      this.decrementClock();
    }, 1000);
  }

然后实现componentDidUpdate这样的方法:

  componentDidUpdate(){
    if(this.state.timer <= 20){
      this.endTimer();
    }
  }

endTimer()像这样:

  endTimer = () => {
      this.setState({
        timing: true,
        timer: 30,
        showWelcome: true,
        timesup: false,
      })
  }

推荐阅读