gpt4 book ai didi

reactjs - 类型错误 : Cannot read property 'url' of undefined/React App crashing

转载 作者:行者123 更新时间:2023-12-04 14:55:22 25 4
gpt4 key购买 nike

我的应用程序在搜索时崩溃了。我怀疑这是因为在渲染过程中的某个时候,艺术家容器正在尝试渲染代码,但是即使我放置了一个备份 URL,也没有图像 url,例如src={props.artist.images[0].url || "backup url"} 它仍然失败。如果你尝试只加载艺术家姓名,我没有问题,但图像是这里的致命弱点。我花了很多时间试图找出它崩溃的原因,但无济于事。

如果我们确实有艺术家结果,艺术家容器也应该只呈现......所以有点困惑为什么它说 URL 未定义。这些结果中 99% 都有图片。

const [query, setQuery] = useState("")
const [artistResults, setArtistResults] = useState(null)

const fetchQueryArtists = async () => {
try {
let response = await fetch(`${ApiUrl}/search?q=${query}&type=artist`, {
headers: {
"Authorization": "Bearer " + props.token
}
})

if (response.ok) {
let json = await response.json()
console.log(json.artists.items)
setArtistResults(json.artists.items)
}
} catch (error) {
console.log(error)
}
}

useEffect(() => {
if (query.length > 1) {
fetchQueryArtists()
fetchQueryTracks()
fetchQueryAlbums()
}
}, [query])

我的返回是这样的:

{query.length > 0 && artistResults &&
<h3 className="py-3 px-2">Artists</h3>}

{artistResults && artistResults.length > 0 ? artistResults.slice(0, 6).map(artist => {
return <ArtistContainer key={artist.id} artist={artist} />
}) : <h1>Test flag</h1>}

这是我的艺术家容器:

return (
<div onClick={directToPlaylist} className="category-container d-flex align-items-center justify-content-center mb-4 col-6 col-md-4 col-lg-3 col-xl-2">
<img className="img-fluid" height={150} src={props.artist.images[0].url} alt="playlist-cover" />
<div>
<span>{props.artist.name}</span>
<p className="text-muted">Artist</p>
</div>
</div>
);

这是 JSON(以防万一你认为我访问图像不正确):

Array(20)
0:
external_urls: {spotify: "https://open.spotify.com/artist/3TVXtAsR1Inumwj472S9r4"}
followers: {href: null, total: 55327781}
genres: (6) ["canadian hip hop", "canadian pop", "hip hop", "pop rap", "rap", "toronto rap"]
href: "https://api.spotify.com/v1/artists/3TVXtAsR1Inumwj472S9r4"
id: "3TVXtAsR1Inumwj472S9r4"
images: Array(3)
0: {height: 640, url: "https://i.scdn.co/image/60cfab40c6bb160a1906be45276829d430058005", width: 640}
1: {height: 320, url: "https://i.scdn.co/image/5ea794cf832550943d5f8122afcf5f23ee9d85b7", width: 320}
2: {height: 160, url: "https://i.scdn.co/image/8eaace74aaca82eaccde400bbcab2653b9cf86e1", width: 160}
length: 3
__proto__: Array(0)
name: "Drake"
popularity: 98
type: "artist"
uri: "spotify:artist:3TVXtAsR1Inumwj472S9r4"
__proto__: Object

最佳答案

使用这个:

src={props.artist.images[0]?.url || "backup url"}

我在这里使用了一种称为可选链接的东西。您可以阅读更多相关信息 here

详细说明:

  1. 在 api 调用之前,react 渲染组件,此时:props.artist.images = [].

  2. 所以在我们获取数据之前,它会是一个空数组,访问它的第一个元素会得到未定义的。

  3. 因此,您尝试访问 undefined.url,这会出错。

现在更多关于可选链:

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

传统上,如果我们必须安全地访问嵌套元素,我们会这样做:

const obj = {
name: {
first: "foo",
last: "bar"
}
};
// Getting first element
const firstName = obj && obj.name && obj.name.first ? obj.name.first : "fallback";

// optional chaining
const firstElement = obj?.name?.first || "fallback"

总结例子:

// This raises TypeError
console.log(undefined.someKey)

// Optinal chaining gives safety net and does not give TypeError
console.log(undefined?.somKey);

关于浏览器支持和使用:由于兼容性问题,这可能不适用于旧版浏览器。检查here

另请注意,如果您使用的是 Typescript > 3.7,则可选链接也适用于旧版浏览器(因为 Babel 会相应地转译以针对已配置的浏览器)。

关于reactjs - 类型错误 : Cannot read property 'url' of undefined/React App crashing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68131309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com