【发布时间】:2016-05-31 12:53:35
【问题描述】:
我正在使用下面的 lib 为每个 ApiRequest 实现回调(onSuccess、onError)。但是在触发事件时更新状态时出现问题。我试图删除所有东西,只保留基本逻辑。我不知道为什么会出错。 库:https://www.npmjs.com/package/react-native-simple-events
下面是我的代码
ApiRequest.js
import Events from 'react-native-simple-events';
export function login(email, password) {
Events.trigger('LoginSuccess', 'response');
}
登录.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>
)
}
}
如果您需要更多信息,请告诉我
【问题讨论】:
-
你检查过
this是否可以在onLoginSuccess函数中访问吗?尝试在onLoginSuccess函数中打印this。如果这无法访问,那么您需要绑定this而你调用onLoginSuccessEvents.on('LoginSuccess', 'myID', this.onLoginSuccess.bind(this));
标签: react-native setstate