我在将数据发布到我fetch
在 react-native 应用程序中使用的快速 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/>
区域:
但是当我提交时,这是显示:
当我改变的身体fetch
是一样的东西
body: JSON.stringify({name: 'some name', description: 'some description'})
它工作正常。所以我认为函数this
内部的值可能不一样fetch
,所以在顶部addData()
我做了一些类似的事情let that = this;
并将我的所有状态变量设置为that.state.name, etc
但仍然不起作用。