javascript - 使用状态解析渲染中的 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)获取内容并将其放置在渲染中。我怎样才能做到?
解决方案
您可以使用 map 函数迭代数据状态并呈现数据状态内的项目列表。
请务必使用${item.WHATEVER_YOUR_FIELD_IS}
内部地图功能。
<div>
{this.state.data.map(item => {
return(
<div>
<h1>${item.username}</h1>
<img src=`${item.imgURL}`/>
</div>
)
})}
</div>
推荐阅读
- shell - 如何使用shell脚本在csv文件的列开头插入值
- docker - Docker 网络模式主机访问 Flask App
- java - 授予 USB 权限后应用程序崩溃 - 使用 aar java 插件的 Unity 应用程序
- reactjs - Web3-React:Walletconnect 未设置活动和帐户在使用Web3React 钩子
- python - 如何根据django中的forgen键集进行反向查询集
- php - 具有默认数组键值
- jasmine - TypeError:无法读取 Jasmine 中未定义(读取“订阅”)的属性
- java - 使用 mybatis 时出现“$3”或附近的语法错误
陈述 - excel-addins - Excel 2013 中的 Microsoft Office Dialog API 身份验证问题
- javascript - 如何在Javascript中更改多维数组中的元素