reactjs - 可以根据 id 找到一个对象,然后在反应组件中渲染它
问题描述
我想根据它找到一个对象,id
然后在组件中渲染它。
getInitialState() {
return { item: [] }
},
componentDidMount() {
this.setState({item: this.props.items.filter(item => (item.id == this.props.match.params.id))})
}
componentDidUpdate() {
console.log(this.state.item) // result is empty array
}
如果我不想setState
在方法中使用和查找对象,render
那么我将得到:
render() {
var item = this.props.items.find(item => (item.id == this.props.match.params.id))
console.log(item) // First it is undefined then it will be found
var title = item.title
return (
<div>
{title}
</div>
如何根据params.id
然后在组件内渲染它来找到对象?
解决方案
render() {
var item = this.props.items.find(item => (item.id == this.props.match.params.id))
//This is what you should do to show that it's loading.
if(!item || !item.id){
return <div>Loading</div>
}
console.log(item) // First it is undefined then it will be found
var title = item.title
return (
<div>
{title}
</div>
推荐阅读
- android - 我们如何从 java 类中向下拉菜单中添加更多项目
- jquery - 为什么数据表使用“.row().remove()”删除其中一行,但多行已被删除?
- python - Dockerfile scrapy 未知命令: crawl
- python - 如何计算3D中两点之间的距离?
- linux - 安排 cronjob 每周将文件复制到不同的位置
- php - 将缩略图图像保存到另一个文件夹 [CodeIgniter]
- python - 试图让 AI 正确调用文本文件中的集合名称
- javascript - 如何在 html 上加载加载器,直到使用 angularjs 加载所有图像?
- mysql - 根据日期列查找唯一项目
- google-analytics - 谷歌分析跟踪代码未触发