【问题标题】:React native JSON and State反应原生 JSON 和状态
【发布时间】: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


【解决方案1】:

我有一个解决方案,也许可以帮助你,首先改变你的get数据,使用return promise,所以我们必须在console.log之前等待这个函数开始

getData(){
  return new Promise ((resolve, reject) => {
    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
      })
      resolve(responseJson);
    })
    .catch((error) => {
      reject(error);
    });
 })
}

然后你可以把你的_onPressButton()改成这个:

_onPressButton() {

    this.getData()
    .then((response) => {
        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})      
      }
    }).catch((error) => {
      console.log(error);
    });
}

希望对你有帮助,谢谢:)

【讨论】:

  • 感谢 val 和 Rizal,两种解决方案都返回正确的数据,但我必须按两次登录。如果我按一次登录,那么什么也不会发生。当第二次按下它时,只会失败消息或重定向到第二个导航页面。知道为什么吗?
  • 运行应用程序 Stockcast2 ({ initialProps = { }; rootTag = 1; }) infoLog.js:17 使用 appParams 运行应用程序“Stockcast2”:{"rootTag":1,"initialProps":{} }。 DEV === true,开发级警告开启,性能优化关闭
  • 在单击登录按钮时输入电子邮件和密码后没有任何反应,但如果我再次单击登录按钮,则导航页面会加载两次。我不确定发生了什么。如有任何帮助,我将不胜感激。
猜你喜欢
  • 2021-03-23
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多