javascript - TypeError:尝试渲染数组时无法读取 ReactJS 中未定义的属性“映射”
问题描述
我正在使用 ReactJS 创建一个网站,但我不断收到如下错误:TypeError: Cannot read property 'map' of undefined,当尝试将数组呈现到主页时。我尝试使用钩子并更改映射的数组,但没有任何效果。
主页:
export default class Home extends Component{
constructor(props){
super(props);
this.state = {
redirect: null,
post:{
username:"",
vidUrl: "",
title:"",
}
};
}
componentDidMount() {
const currentUser = AuthService.getCurrentUser();
if(!currentUser) this.setState({ redirect: "/login"});
this.setState({ currentUser: currentUser, userReady:true});
PostService.return().then(result => result.data.videos.map((results) => {
this.setState({ post:{username:results.username,vidUrl:results.vidUrl,title:results.title}})
console.log(this.state.post)
}))
}
render(){
if(this.state.redirect){
return <Redirect to={this.state.redirect} />
}
return(
<div>
{
this.post.map((result) => (
<Post key={result._id} username={result.username} caption={result.title} vidUrl={result.vidUrl}/>
))
}
</div>
)
}
}
邮政:
export default function Post({username,caption,vidUrl,user}){
return(
<div className="header">
<div className="videoContain">
<div className="info-Contian">
<Avatar className="Avatar" />
<p className="Caption">{username}</p>
</div>
<video className="video" src={vidUrl} controls>
<p>If you are reading this, it is because your browser does not support the 'video' element. Try using the 'object' element listed further down the page.</p>
</video>
<br/>
<FaHeart className="Heart" size="2em" />
<FaComment className="Comment" size="2em" />
<br/>
<p>{caption}</p>
</div>
</div>
)
}
这就是我要渲染的内容:
{
"videos": [
{
"_id": "612d89284c5c4e9e42cf4fa5",
"username": "qwerty",
"title": "stuff",
"vidUrl": "blob:http://localhost:3000/fd2ba95b-480a-4a46-baf0-8423e1163f7e",
"comments": [],
"likes": [],
"__v": 0
},
{
"_id": "613412b7b13bc4c1b4f4433f",
"username": "name",
"title": "also a test",
"vidUrl": "blob:http://localhost:3000/4ca89ae2-0d1c-4e03-8738-87d7ea29081f",
"comments": [],
"likes": [],
"__v": 0
}
]
}
解决方案
您的代码中有几个问题:
首先,要获得map
作品,post
状态应该被定义为一个数组
this.state = {
redirect: null,
post: []
};
其次,你不应该setState
在 a map
, oncepost
是一个数组,简单地这样做:
PostService.return().then(result => this.setState({ post: result.data.videos }))
最后一个是this.post
应该render
的this.state.post
。
推荐阅读
- sql - 在 SQL Server 中锁定多个表
- maps - 填充MRPT velodyne扫描观察
- garmin - Garmin 应用程序步数、活动和睡眠数据
- ssl - 无法在 Centos7 apache2 上安装 Comodo SSL 证书
- c# - 在预制件中存储对场景对象的引用?
- angular - 如何在此代码中将此管道与另一个管道一起使用以过滤 Angular 中的数据?
- javascript - videojs 插件的 currentTime() 方法不起作用
- java - Travis CI 上不同版本的 java 和 javac
- java - Spring Scheduler 使用 cron 表达式与固定延迟的优势
- javafx - fxml 包括其他 fxml 文件和用户定义的属性