簡體   English   中英

如何在反應組件中呈現狀態數組。 該數組在狀態下可用,但在呈現其顯示未定義時

[英]how to render the state array in react component. the array is available in state but while rendering its showing undefined

我想將數據從 firestore 渲染到我的反應組件中。 我用 firestore 數據更新了全局狀態數組,它正在更新,但是當我要渲染該數組時,該數組顯示為未定義。

我曾嘗試使用 redux 並且發生了同樣的問題,現在使用 reactn 但發生了同樣的事情。

import React from "react";
import {setGlobal} from "reactn";
import ReactDOM from "react-dom";
import Apps from "./Apps";

setGlobal({  names:[],})

ReactDOM.render( <Apps/>, document.getElementById("root"))
ReactDOM.render(<Apps/>, document.getElementById("root"))`

-----App.js----------

import React from "reactn";
import db from "./firebase";

class Apps extends React.Component{

    componentDidMount(){
        db.collection("users").get().then((snapshot)=>{

            snapshot.forEach((doc)=>{

            const user=  {name:doc.data().name,
               weight:doc.data().weight,
             id:doc.id}
             this.global.names.push(user)
          })       
    })
}

render(){
        ///this show the data in names array of state
        console.log(this.global)
        //// this show undefind (its having data)
        console.log(this.global.names[0])
        return(
            ///but while rendering its not showing anything
            <div>{this.global.names.map((name)=>(
                <h1>weight is {name.weight} </h1>
            )
            )}</div>
        )
    }
}

export default Apps;

代替

this.global.names.push(user)

你必須使用

this.setGlobal(names: names.push(user))

我認為不要在反應中使用全局變量只是做類似的事情

class Apps extends React.Component {

constructor(props) {
    super(props)
    this.state = {
        names: [],
    }
}

componentDidMount() {

    let array = [];
    db.collection("users").get()
        .then((snapshot) => {

            snapshot.forEach((doc) => {

                const user = {
                    name: doc.data().name,
                    weight: doc.data().weight,
                    id: doc.id
                }
                array.push(user)
            })
        })
        .then(() => {
            this.setState({
                names : array
            })
        })
}

render() {
    ///this show the data in names array of state
    console.log(this.state.names)
    //// this show undefind (its having data)
    console.log(this.state.names[0])
    return (
        ///but while rendering its not showing anything
        <div>{this.state.names.map((name) => (
            <h1>weight is {name.weight} </h1>
        )
        )}</div>
    )
}
}

export default Apps;

試試這個並告訴我它是否有效:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM