如何从componentDidMount调用成员函数

时间:2016-07-18 11:23:02

标签: javascript reactjs react-native

我试图在调用getCurrentPosition()之后从componentDidMount()调用一个函数。如果我将位置传递给updatePosition应用程序崩溃。如果我将updatePosition函数的内容移动到getCurrentPosition(),那么它的工作原理。我需要做什么才能从componentDidMount()中调用成员函数。

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

      this.state = {
        lat: 0,
        long: 0,
        heading: 0,
        accuracy: 0,
        speed: 0,
        pointCount: 0
      };
  }

  updatePostion(position) {
    var lat = position.coords.latitude;
    this.setState({lat});
  }

  componentDidMount() {
    let self = this;

    setInterval(() => {
      navigator.geolocation.getCurrentPosition((position) => {
        // this breaks
        this.updatePostion(position);

        // if I place the body of updatePosition here it works.
      },
       (error) => {},
       {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
      );
    }, 5000);
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: 'black'}}>
        <View style={{flex: 1, color: 'green'}}>
          <Text style={styles.green}>
            Position: {this.state.lat}, {this.state.long}
          </Text>
          <Text style={styles.green}>
            Heading: {this.state.heading}
          </Text>
          <Text style={styles.green}>
            Speed: {this.state.speed}
          </Text>
          <Text style={styles.green}>
            Accuracy: {this.state.accuracy}
          </Text>
          <Text style={styles.green}>
            Point Count: {this.state.pointCount}
          </Text>
        </View>
      </View>
    );
  }
}

3 个答案:

答案 0 :(得分:1)

实际上,一切正常!这是RNplay example及其代码:

'use strict';

var React = require('react');
var {
  Component,
} = React;
var ReactNative = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = ReactNative;

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

      this.state = {
        lat: 0,
        long: 0,
        heading: 0,
        accuracy: 0,
        speed: 0,
        pointCount: 0
      };
  }

  updatePostion(position) {
    var lat = position.coords.latitude;
    this.setState({lat});
  }

  componentDidMount() {
    setInterval(() => {
      navigator.geolocation.getCurrentPosition((position) => {
        this.updatePostion(position);
      },
       (error) => {},
       {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
      );
    }, 5000);
  }

  render() {
    console.log(this.state);
    return (
      <View style={{flex: 1, padding: 30}}>
        <View style={{flex: 1}}>
          <Text>
            Position: {this.state.lat}, {this.state.long}
          </Text>
          <Text>
            Heading: {this.state.heading}
          </Text>
          <Text>
            Speed: {this.state.speed}
          </Text>
          <Text>
            Accuracy: {this.state.accuracy}
          </Text>
          <Text>
            Point Count: {this.state.pointCount}
          </Text>
        </View>
      </View>
    );
  }
}

AppRegistry.registerComponent('SampleApp', () => GeolocationViewer);

(查看控制台日志)

答案 1 :(得分:0)

'self'没有在updatePostion()中定义,这就是你有错误的原因

updatePostion(position) {
    // replace self with this
    self.setState({position.coords.latitude});
}

你也不需要这个

let self = this;

在componentDidMount()内部,因为你使用箭头函数

答案 2 :(得分:0)

我知道这看起来很丑陋,但是当你做出你将要面对的反应时,这是常见的问题。 var request = new HttpRequest("/", ConfigFile.Url, ""); var response = new HttpResponse(new StringWriter()); httpContext = new HttpContext(request, response); var httpContextBase = new HttpContextWrapper(httpContext); var routeData = new RouteData(); var requestContext = new RequestContext(httpContextBase, routeData); var urlHelper = new UrlHelper(requestContext); var url = urlHelper.Action("Index", "Item", new { ItemId = model.itemId}); 内的绑定成员函数(ES7可能会让它看起来更好,但这将是很长时间等待)

Devise.password_length.include?(user[:password].length)