首页 > 解决方案 > 使用状态解析渲染中的 componentDidMount 值

问题描述

我是使用反应的新手。我想从 firebase 获取内容并在渲染中解析它。所以我尝试:

constructor(props) {
    super(props);
    this.state = {
        loading: true,
        data: null
    }
}


componentDidMount() {
    var feedRef = firebase.database().ref().child('posts').limitToLast(10);
    feedRef.once('value', async function(snapshot) {

        this.setState({ data: snapshot.val(), loading: false }); // error Unhandled Rejection (TypeError): Cannot read property 'setState' of null

    });
}

render() {

    return this.state.loading ? (
        <div>
            <Spinner />
        </div>
    ) : (

        <>
                <div>
                    // how to put firebase content here?
                </div>
        </>

    );
}

我想从firebase(用户名,img)获取内容并将其放置在渲染中。我怎样才能做到?

标签: javascriptreactjsfirebase-realtime-database

解决方案


您可以使用 map 函数迭代数据状态并呈现数据状态内的项目列表。
请务必使用${item.WHATEVER_YOUR_FIELD_IS}内部地图功能。

<div>
   {this.state.data.map(item => {

     return(
      <div>
         <h1>${item.username}</h1>
         <img src=`${item.imgURL}`/>
      </div>
   )
})}
</div>

推荐阅读