【发布时间】:2017-07-31 15:37:25
【问题描述】:
我对本机反应和一般编程是新手。我在这里需要帮助。
我有一个简单的登录屏幕,用户可以在其中输入电子邮件和密码。当用户单击登录按钮时,我会调用我的网络服务来检查我的数据库中匹配记录的数量,以查找该电子邮件/密码组合。 Web 服务以 JSON 格式返回计数。但我数不清了。我怀疑这与设置状态有关。
来自网络服务的 JSON: {"订阅者":[{"count":"0"}]}
这是我的代码:
constructor(props) {
super(props)
this.state = {
email: '',
password: '',
uCount: '',
data: []
};
}
_onPressButton() {
this.getData();
console.log("email:", this.state.email);
console.log("passwd:", this.state.password);
console.log("data", this.state.data);
console.log("uCount", this.state.uCount);
if (this.state.uCount < 1) {
Alert.alert('Fail')
} else {
this.props.navigation.navigate('LoginSuccess', { email: this.state.email, password: this.state.password})
}
}
getData(){
var url="myurl.php?email=" + this.state.email + "&password=" + this.state.password;
console.log("URL:", url);
return fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.Subscriber,
uCount: responseJson.Subscriber[0].count
})
})
.catch((error) => {
console.error(error);
});
}
点击按钮我正在调用 _onPressButton 函数,该函数调用 getData 函数来调用 Web 服务并从 JSON 中获取计数。我已经验证了 url 构造是正确的,并且它返回了正确的 JSON。当我打印时
console.log("data", this.state.data);
console.log("uCount", this.state.uCount);
调用getData函数后数据数组为null,初始化时count为空
data []
uCount
这意味着下面的代码不起作用。
.then((responseJson) => {
this.setState({
data: responseJson.Subscriber,
uCount: responseJson.Subscriber[0].count
})
请帮忙。
【问题讨论】:
-
试试
console.log(responseJson)?里面有什么 -
对象 {Subscriber: Array(1)} Subscriber : Array(1) 0 : Object count : "0" proto : Object length : 1 proto : Array(0) proto : Object
-
responseJson 显示正确的对象
-
您在
_onPressButton()中的console.log没有为您提供正确的信息。你setState在promise.then里面,这是一个异步响应,但是 console.log 它是同步的。 -
用
async _onPressButton() { await this.getData();再试一次?
标签: react-native