当我尝试将变量发布为时,它失败了:
body: JSON.stringify({
username: this.state.username, // it doesn't work,
}),
但是一切都很好,如果发布为:
body: JSON.stringify({
username: 'literal string', // it works well
}),
我可以从console.log中获取this.state.username的正确值,那么帖子上的问题是什么?这是完整的代码:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
} from 'react-native';
const REQUEST_URL = 'http://localhost:8000/user';
export default class AddAUser extends Component {
constructor(props) {
super(props);
this.state = {
username: null,
submit: false,
}
}
async _signup() {
try {
await this.setState({
username: this.state.username,
submit: true
});
let response = await fetch(REQUEST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username, // it doesn't work,
// username: console.log(this.state.username), // get correct value from TextInput
// username: 'literal string', // it works well
}),
});
await console.log(response);
} catch (error) {
console.log(error);
}
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.textInputBox} placeholder='Username' value={this.state.username} onChangeText={(username) => this.setState({username: username})} />
<TouchableOpacity
style={styles.submitButton}
onPress={() => this._signup()}
>
<Text>Sign Up</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
textInputBox: {
height: 40,
borderColor: 'lightblue',
borderWidth: 1,
borderRadius: 5,
margin: 20,
paddingLeft: 10,
},
submitButton: {
marginTop: 20,
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 20,
paddingRight: 20,
backgroundColor: 'lightblue',
borderRadius: 5,
}
});
我不确定您要使用using实现什么async + await
,上下文中没有解释。
我在以下网址尝试了没有它们的情况:https : //rnplay.org/apps/8U6_sA,它似乎按预期工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句