gpt4 book ai didi

javascript - 如何在获取请求React Native中使用响应

转载 作者:行者123 更新时间:2023-12-01 02:34:00 25 4
gpt4 key购买 nike

我是 React Native 世界和(JS)的新手。我想将电话号码密码发送到服务器以进行登录。我可以发送数据并接收响应,但是,我不知道应该如何处理响应。我有一个名为 _response_recognizer 的函数。但它不起作用。甚至setStat。所有教程仅介绍如何连接到服务器以及如何从中获取数据。在我的登录表单中使用响应的最佳方法是什么?如果它的状态是 200,我想导航到另一个屏幕,否则我想吐槽一条消息。

import React, {Component} from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TextInput, Button
} from 'react-native';

export default class LoginForm extends Component<{}> {
constructor(props) {
super(props);
this._onLogInPressed = this._onLogInPressed.bind(this);
this._response_recognizer = this._response_recognizer.bind(this);
this.state = {
phone_number: '',
password: '',
data: {}
};
}
_response_recognizer(data: string ){

}

_onLogInPressed = () => {

var data = {
'phone_number': this.state.phone_number,
'password': this.state.password
}


fetch("http://192.168.1.12:5000/login", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}).then(function(response){
return response.json();
}).then(function(data){
console.log(data)
this._response_recognizer(data)
}) .catch((error) => {
console.log("Error" + error);
});
};

render() {
return (
<View style={styles.flow}>
<Text style={styles.text}>phone number:</Text>
<TextInput keyboardType='numeric'
style={styles.input}
ref="phone_number"
onChangeText={(phone_number) => this.setState({phone_number})}
maxLengt={11}
value={this.state.phone_number}
/>
<Text style={styles.text}>password:</Text>
<TextInput style={styles.input} secureTextEntry={true} ref="password"
onChangeText={(password) => this.setState({password})}
value={this.state.password}/>
<Button style={styles.button} onPress={this._onLogInPressed} title='login'/>
</View>
);
}
}

最佳答案

有两件事。

您的 _response_recognizer 函数正在请求 data: string,但您返回的是 json object:

.then(function(response){
return response.json();
}).then(function(data){
console.log(data)
this._response_recognizer(data)
})

将其更改为data: object

其次,您在 .then 中使用函数声明 (function(){})。如果不直接绑定(bind) this,您就会失去 Class 函数的范围。将它们更改为箭头函数 (() => {}) 以解决范围问题:

.then((response) => response.json())
.then((data) => {
console.log(data)
this._response_recognizer(data)
})

您还可以选择删除 .then 操作之一:

.then((response) => {
console.log(response.json())
this._response_recognizer(response.json())
})

✌🏾

关于javascript - 如何在获取请求React Native中使用响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48084775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com