Undefined不是评估this.state的对象。*

时间:2016-11-06 03:13:14

标签: javascript reactjs react-native

我遇到了将数据发布到我在react-native应用中使用fetch的快速REST API的问题。这是我的代码:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
import Button from 'react-native-button';
import DeviceInfo from 'react-native-device-info'

export default class ReliefMobile extends Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {
      currentLocation: {latitude: 40.6391, longitude: 10.9969},
      name: 'Some dumb name',
      description: 'Some dumb description',
      deviceId: DeviceInfo.getUniqueID()
    }
  }

  addData() {
    fetch('http://localhost:3000/api/effort/add', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        name: this.state.name,
        description: this.state.description,
        deviceId: this.state.deviceId,
        currentLocation: this.state.currentLocation
      })
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native
        </Text>
        <Text style={styles.instructions}>
          Your device ID is {DeviceInfo.getUniqueID()}
        </Text>
        <Text style={styles.instructions}>
        Effort Name: {this.state.name}
        </Text>
        <Text style={styles.instructions}>
        Effort Description: {this.state.description}
        </Text>
        <Text style={styles.instructions}>
        Location: {this.state.currentLocation.latitude}, {this.state.currentLocation.longitude}
        </Text>
        <Button onPress={this.addData}>Add data</Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('ReliefMobile', () => ReliefMobile);

当我尝试按下我的按钮来调用addData功能时,我收到此错误:undefined is not an object (evaluating this.state.name)

在加载应用时,我的状态变量似乎正好加载到<Text/>区域:

Imgur

但是当我提交时,这是显示的: Imgur

当我将fetch的正文改为

body: JSON.stringify({name: 'some name', description: 'some description'})

工作正常。所以我认为this函数中fetch的价值可能不一样,所以在addData()的顶部,我做了let that = this;之类的事情并设置了我的所有内容状态变量到that.state.name, etc但仍然无效。

4 个答案:

答案 0 :(得分:24)

可能你需要绑定上下文。在 onClick 方法中添加以下内容:onClick={this.addData.bind(this)}。这样,该方法可以访问状态对象。

答案 1 :(得分:6)

React处理程序不会自动绑定到它们所在的元素/类。

<Button onPress={this.addData.bind(this)}>Add data</Button>

https://facebook.github.io/react/docs/handling-events.html

摘自上面的链接

// This syntax ensures `this` is bound within handleClick
return (
  <button onClick={(e) => this.handleClick(e)}>
    Click me
  </button>
);

答案 2 :(得分:3)

您应该在构造函数中绑定而不是在render函数中。在构造函数中,只需添加:

this.addData = this.addDate.bind(this);

您也可以使用ES6作为另一种选择:

addData = () => { ... }

这将在此处记录:箭头功能部分下的https://babeljs.io/blog/2015/06/07/react-on-es6-plus

答案 3 :(得分:-2)

在有反应的情况下,使addData()成为这样的箭头函数:

addData = () => {

    ... 

}