尝试使用数组映射函数时,React属性未定义



我从API接收到一个对象,其中包含一些简单的属性和一个字符串数组。我正试图使用map函数来显示这个数组,尽管当我尝试使用map函数时,我的应用程序会中断投掷";TypeError:标记未定义;。代码:

import React, { Component } from 'react';
import {useParams} from "react-router-dom";
import VideoPlayer from "../Video/VideoPlayer";
import { withRouter } from "react-router";
class VideoDetails extends Component {
constructor(props) {
super(props);
this.state = 
{
video: {}
}
}
componentDidMount() {
const url = "https://localhost:44362/api/Video/" + this.props.id;
fetch(url)
.then(resp => resp.json())
.then(json => this.setState({ video: json }))
}
render() {
const {video} = this.state;
const tags = video.tags;
console.log(tags);
console.log(video);
return (
<div>
<h1>{video.title}</h1>
<VideoPlayer />
<h2>Video ID {video.id}</h2>
<br></br>
<h3>Description</h3>
<p>{video.description}</p>
<h3>Tags</h3>
<ul>
{
tags.map(
(tag) => 
(
<li>{tag}</li>
)
)
}
</ul>
</div>
);
}
}
export default VideoDetails;

我有一种感觉,它不知道video.tags是一个数组,但我不太确定如何解决这个问题。我可以删除map函数,直接打印出数组,但map不起作用。我不太清楚我做错了什么,我遇到的很多例子似乎都是直接处理数组的。

我认为这是因为最初您的状态对象-视频是空的。componentDidMount将在客户端上的第一次渲染之后执行。因此,基本上,将首先调用render方法,然后调用componentDidMount。因此,由于最初在视频状态对象中没有标记键,所以const-tags变量是未定义的。

您应该在渲染方法中添加一个检查,以检查在渲染过程中是否存在标记数组。

问题:这里的问题是,您的组件正试图呈现";标签";在它被提取之前或在它被设置为数组之前。

解决方案:

  1. 给标签一个默认值0。

    this.state = { video: { tags:0} }

2(更改地图部分

{
this.state.video.tags===0?'Loading':this.state.video.tags.map( (tag) => 
(
<li>{tag}</li>
)
)
}

这是因为一旦组件第一次呈现,您就试图在tags属性上运行循环(在初始页面加载时未定义(。尝试以下条件以防止问题

{tags && tags.map((tag) => <li>{tag}</li>) }

最新更新