状态更改,组件重新渲染React Native

时间:2018-12-08 20:08:27

标签: reactjs react-native

我有2个倒数计时。

{First滴答滴答声1分钟会增加+1,以便在每次重新开始倒计时时进行计数。

Second滴答滴答表示每2分钟倒数重新开始,每2分钟加+2即可计数。

秒数永远不会达到0,1分钟后的第一个倒数计时会重置(更改状态),然后两个倒数计时都会重新开始。有什么办法可以做到吗?

export default class App extends Component {
  state = {
  seconds: 1000 * 60,
  seconds2: 2100 * 60,
  count: 0,
  exp: 0,
};

render(){
return(

<View>
   <TimerCountdown
     initialSecondsRemaining={this.state.seconds}
     onTimeElapsed={() => this.setState({seconds: 1500 * 60, count: this.state.count+1, exp: this.state.exp+1})}
     allowFontScaling={true}
     style={styles.clock}
   />

   <TimerCountdown
     initialSecondsRemaining={this.state.seconds2}
     onTimeElapsed={() => this.setState({seconds2: 2000 * 60, count: this.state.count+2, exp: this.state.exp+2})}
     allowFontScaling={true}
     style={styles.clock}
   />
</View>
);

1 个答案:

答案 0 :(得分:0)

问题是:状态更改->反应重新渲染->计时器重启 为了解决这个问题,请在单独的类中定义计时器,如下所示:

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import TimerCountdown from 'react-native-timer-countdown';


class Timer extends React.Component {
  constructor(props){
      super(props);
        this.state = {
        seconds: this.props.seconds,
      };
    }
  render(){
    return (
      <TimerCountdown
        initialSecondsRemaining={this.state.seconds}
        onTimeElapsed={() => {
          this.setState({seconds: this.props.seconds});
          this.props.onTimeElapsed();
        }}
        allowFontScaling={true}
      />
    );
  }
}


class App extends React.Component {
  state = {
    seconds: 1000 * 60,
    seconds2: 2100 * 60,
    count: 0,
    exp: 0,
  };
  render() {
    return (<View>

      <Timer 
        seconds={this.state.seconds}
        onTimeElapsed={() => this.setState({seconds: 1500 * 60, count: this.state.count+1, exp: this.state.exp+1})}
      />
      <Timer 
        seconds={this.state.seconds2}
        onTimeElapsed={() => this.setState({seconds2: 2000 * 60, count: this.state.count+2, exp: this.state.exp+2})}
      />
    </View>);
  }
}

export default App;