文本输入 onSubmit 同时使用 fetch React Native



我正在尝试通过textInput更新昵称和电子邮件的状态,然后通过post请求将其提交给我的服务器。两者都以未定义的身份不断返回。我完全不知道我在这里做错了什么。

export default class Add extends Component {
constructor(props){
super(props);
this.state ={ 
isLoading: true,
nickname: "",
email: ""
}
}
static navigationOptions = {
title: 'Add Contacts',
};
componentDidMount(){
this.setState({
isLoading: false
})
}
onSubmit = () => {
console.log('on submit')
return fetch(`...`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain */*',
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state)    
})
.then((response) => response)
.then((responseJson) => {
return responseJson
})
.catch((error) => {
throw error;
})
}
render() {
const { navigate } = this.props.navigation;
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View 
style={styles.container}
>
<Text 
style={{fontSize:30}}>
New Contact
</Text>
<View>
<TextInput 
ref= {(el) => { this.nickname = el; }} 
onChangeText={(nickname) => this.setState({nickname}, function () {console.log('Nickname updated')})}
value={this.state.nickname}
/>
<TextInput 
value={this.state.email}
onChangeText={(text) => this.setState({email: text})}   
/>
</View>
<Button
text = {
<Text 
style={{color:colors.textColor, textAlign: 'center'}}
> 
Save 
</Text>
} 
onPress= { () => {
this.onSubmit()
navigate('Home')
}
}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: 20,
alignItems: 'center',
justifyContent: 'center',
}
});
.then((response) => response)

应该是:

.then((response) => response.json())

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Making_fetch_requests

最新更新