如何从回调函数访问状态

111*_*110 5 javascript ecmascript-6 reactjs react-native

我在 react native 中有一个组件:

export default class Screen extends Component {
  constructor(props){
    super(props);
    this.state = {
      prop1: false,
      prop2: simpleFunc
    };
  }
  simpleFunc = () => { /*...*/ }

  componentWillMount() {
      BackgroundGeolocation.on('location', this.onLocation);
Run Code Online (Sandbox Code Playgroud)

最后一行是将在新位置调用的回调方法。
从该方法我无法访问this.statethis.simpleFunc().

我应该怎么做才能从回调函数更新状态?

Dav*_*yon 5

为了访问this内部,onLocation您需要绑定回调:

  componentWillMount() {
      BackgroundGeolocation.on('location', this.onLocation.bind(this));
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用箭头函数(它将使用父级的词法范围):

  componentWillMount() {
      BackgroundGeolocation.on('location', (location) => this.onLocation(location));
Run Code Online (Sandbox Code Playgroud)