1

I'm using below lib to implement a callback (onSuccess, onError) for every ApiRequest. But I have a problem when update state when event is trigged. I tried to remove all stuffs just keep the base logic. I don't know why it error. Lib: https://www.npmjs.com/package/react-native-simple-events

Below is my code

ApiRequest.js

import Events from 'react-native-simple-events';
export function login(email, password) {
       Events.trigger('LoginSuccess', 'response');
}

Login.js

import React, { Component, } from 'react'
import {
  View,
  Text,
} from 'react-native'
import Events from 'react-native-simple-events';

import * as request from '../../network/ApiRequest'
class LoginScreen extends Component {

  static propTypes = {}

  static defaultProps = {}

  constructor(props) {
    super(props)
    this.state = {
      status: "new"
    }
  }

  componentDidMount() {
    Events.on('LoginSuccess', 'myID', this.onLoginSuccess); 
    request.login("abc","def")

  }
    componentWillUnmount() {

      Events.rm('LoginSuccess', 'myID');

    }

  onLoginSuccess(data){ 
    this.setState({ //=>error here
       status : "done"
    });
  }
  render() {
    return (
      <View>
        <Text>
          {this.state.status}
        </Text>
      </View>
    )
  }
}

let me know if you need more information

4

1 回答 1

1

您需要在onLoginSuccess方法上绑定它:

Events.on('LoginSuccess', 'myID', this.onLoginSuccess.bind(this));
于 2016-05-31T13:41:04.077 回答