简体   繁体   中英

React Native - use a state variable in a static function

I'm new to React-Native, i have a problem creating my app. Basically, i have a main application that do things, one of those is setting a Date variable in state called: sleepTime. Now i've created a clock that works perfectly and every seconds is updated. My problem now is to create a function into my main application that compare the actual date (given from the clock) with the date saved before. The problem is that i've used a static function wich is called on every tick in the clock class, this function (compareTime()) is in the main class and obviusly i get the "undefined is not an object" when I call it. What i can't figure out is how to link the call made by clock with the date that i've saved before.

This is the static function:

static compareTime(){
  const sleepTime = this.state.sleepTime;
      if(new Date().toLocaleString() == sleepTime){
        this.stopTimer();
      }
 }

Clock class:

class Clock extends React.Component {
          constructor(props) {
            super(props);
            this.state = {
              time: new Date().toLocaleString()
            };
          }
          componentDidMount() {
            this.intervalID = setInterval(
              () => this.tick(),
              1000
            );
          }
          componentWillUnmount() {
            clearInterval(this.intervalID);
          }
          tick() {
            this.setState({
              time: new Date().toLocaleString()
            });
            MainPage.compareTime();
          }

          render() {
            return (
              <Text style={styles.greeting}>
                The time is: {this.state.time}
              </Text>
            );
          }
        }

And the return of the main render wich is the only thing that links main and clock:

 return (
      <View style={styles.container}>
        <Clock />
        <Text style={styles.greeting}>
            Sleep time: {sleepTime}.
        </Text>
      </View>
 )

You can use props for that. Since the is a subcomponent of MainApplication, you can pass the function comparetime() to the as props and this function can be called from within the

The main render would have,

<Clock compareTime={this.compareTime.bind(this)}/>

And the Clock class can use the function from props,

tick() {
  this.setState({
    time: new Date().toLocaleString()
  });
  this.props.compareTime();
}

You can also pass parameters if you want to get values from Clock class to Main.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM