【问题标题】:JavaScript array's properties undefined while array is readable (iOS)JavaScript 数组的属性未定义,而数组可读(iOS)
【发布时间】:2018-12-01 19:56:38
【问题描述】:

目前正在使用 react-native-sqlite-storage 开发 React Native (iOS)。 getUserData 函数由组件(ProfileView)调用,然后它只是记录它。 如果我尝试记录返回的数组,它可以工作,但如果我尝试记录同一个数组的零元素,它会说它是未定义的。 我省略了 okCallback 和 errorCallback,因为它们只是 console.log 发送给它们的消息。 我也尝试在 getUserData 中使用对象而不是数组,但它只会返回 undefined。

数据库工作者:

export function getUserData() {
    var arr = [];
    db.executeSql('SELECT * from userData;', [], results => {
        let len = results.rows.length;
        for(let i = 0; i < len; i++) {
            arr.push(results.rows.item(i));
        }
    });
    return arr;
}

class ProfileView extends React.Component {
    constructor(props) {
        super(props);
        var test = getUserData();
        console.log('not working', test[0])
        console.log('working', test)

    }

个人资料视图:

class ProfileView extends React.Component {
constructor(props) {
    super(props);
    var test = getUserData();
    console.log('not working', test[0])
    console.log('working', test)

}

render() {
    return (...);
}
}

提前致谢

【问题讨论】:

  • 这能回答你的问题吗:stackoverflow.com/questions/14220321/…
  • 所以console.log('working', test) 有效,但console.log('not working', test[0]) 无效?
  • 你的问题是时间。您不能检查明天要填写的框的内容。与您无法检查数组内容的方式相同,它将被填充(比方说)20ms。

标签: javascript ios arrays react-native


【解决方案1】:

正如@Thomas 所说,这是时间问题。

您的数据库调用是异步的。您创建一个空数组。然后你向db.executeSql 提供一个回调函数。每当数据库返回数据时,就会调用该回调函数,并将元素添加到数组中。

但是,当这种情况发生时,您的事件循环会继续进行。在您的情况下,您将返回(空)数组并执行您的console.logs。

为了使这项工作可靠,您必须在组件中有一种机制来监视数据库调用是否完成,以及何时使用数据。通常这就是反应组件状态的用途。

所以我们创建了一个状态,然后我们将一个回调传递给我们的getUserData。当数据库调用完成时,它会更新我们的状态,并且组件会重新渲染。

export function getUserData(cb) {
  var arr = [];
  db.executeSql('SELECT * from userData;', [], results => {
    let len = results.rows.length;
    for (let i = 0; i < len; i++) {
      arr.push(results.rows.item(i));
    }
    if (cb) cb(arr);
  });
  return arr;
}

个人资料视图:

class ProfileView extends React.Component {
  constructor(props) {
    super(props);
    this.state = { test: [] };
    var test = getUserData(x => this.setState({ test: x }));
  }

  render() {
    if(this.state.test.length) console.log('not working', this.state.test[0]);
    console.log('working', this.state.test);
    return (...);
  }
}

【讨论】:

  • 感谢您的回答,但问题仍然存在。我将 getUserData 调用移动到 componentWillMount 并将其存储在组件的状态中,然后如果我调用 this.state 它会返回包含用户数据的状态,但是如果假设数据存储在 this.state.data 中数组,我做 this.state.data[0] 它返回 undefined。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 2018-07-20
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多