StephenGrider / ReactNativeCasts

MIT License
186 stars 87 forks source link

Cannot read property 'timeElapsed' of null #5

Open gHashTag opened 8 years ago

gHashTag commented 8 years ago

Why?

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native';

class stopwatch extends Component {
  getInitialState() {
    return {
      timeElapsed: null
    }
  }

  startStopButton() {
    return (
      <TouchableHighlight
        underlayColor="gray"
        onPress={this.handleStartPress}>
        <Text>
          Start
        </Text>
      </TouchableHighlight>
    )
  }

  lapButton() {
    return (
      <View>
        <Text>
          Lap
        </Text>
      </View>
    )
  }

  handleStartPress() {
    var startTime = new Date();

    setInterval(() => {
      this.setState({
        timeElapsed: new Date() - startTime
      });
    }, 30);

  }

  border(color) {
    return {
      borderColor: color,
      borderWidth: 4
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={[styles.header, this.border('yellow')]}>
          <View>
            <Text style={[styles.timerWrapper, this.border('red')]}>
              {this.state.timeElapsed}
            </Text>
          </View>
          <View style={[styles.buttonWrapper, this.border('green')]}>
            {this.startStopButton()}
            {this.lapButton()}
          </View>
        </View>
        <View style={[styles.footer, this.border('blue')]}>
            <Text>
                I am List of Laps
            </Text>
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'stretch'
  },
  header: {
    flex: 1
  },
  footer: {
    flex: 1
  },
  timerWrapper: {
    flex: 5,
    justifyContent: 'center',
    alignItems: 'center'
  },
  buttonWrapper: {
    flex: 3,
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center'
  }
});

AppRegistry.registerComponent('stopwatch', () => stopwatch);
patrykkopycinski commented 8 years ago

hey @gHashTag, i think the problem is with

getInitialState() {
    return {
      timeElapsed: null
    }
  }

getInitialState isn't valid as you use es6 class, instead of you should define initial state in the constructor like

class stopwatch extends Component {
  constructor(props) {
    super(props);

    this.state = {
      timeElapsed: null
    };
  }

  ...
}