【问题标题】:React-Native error this.setState is not a functionReact-Native 错误 this.setState 不是函数
【发布时间】: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 而你调用 onLoginSuccess Events.on('LoginSuccess', 'myID', this.onLoginSuccess.bind(this));

标签: react-native setstate


【解决方案1】:

你需要在onLoginSuccess方法上绑定这个:

Events.on('LoginSuccess', 'myID', this.onLoginSuccess.bind(this));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2022-06-26
    • 2019-04-21
    相关资源
    最近更新 更多