javascript - 由于某种原因在 native react 中渲染后发生 ComponentWillMount

标签 javascript reactjs firebase react-native

    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}

我正在尝试从数据库获取数据并将其放入 highscoreArray 中。然后我尝试将其作为渲染中的文本。由于某种原因它是空的或为空。这意味着 componentWillMount() 在 render() 之后发生

有人可以解释或让这个工作吗?我很沮丧。

我已经更改了代码,因为人们帮助了我,但它仍然给出错误:

undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')

最佳答案

Data stored in a Firebase Realtime Database is retrieved by attaching an asynchronous listener to a database reference

根据documentation .

因此,在不知道结果之前,以下代码 this.state.highscoreArray[0]["score"].toString() 将返回错误。在显示结果之前,检查 highscoreArray 是否包含某些项目。

此外,检索数据并不是一个好的做法。看看React component lifecycle :

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method

关于javascript - 由于某种原因在 native react 中渲染后发生 ComponentWillMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44893816/

相关文章:

javascript - 将日期字符串转换为日期对象 Javascript

javascript - 为什么我的单例无法工作?

node.js - 尝试使用 this.refs.value 时,使用 this.refs 已被弃用错误

angular - valueChanges() 仅返回列表更改的受影响项目

javascript - ReactJs:从数组创建组件会导致旧 Prop

javascript - Cordova 没有给出想要的结果

javascript - 是否可以控制无法控制的输入文本? - react

jquery - 在 Bootstrap 弹出窗口中渲染 React 组件

html - 错误 : Reference. 推送失败:第一个参数在属性中包含一个函数 - firebase

android - Firebase 测试实验室 CI 上传 apk