如何在React应用程序中访问获取的json值

问题描述 投票:0回答:1

这是我在该平台上的第一篇文章。我希望它会很清楚。

我正在使用 tmdb API 开发一个 React 电影应用程序。提取工作并返回 20 个对象(电影)的数组。我可以映射数组访问所有电影的值,但我无法对某一特定电影执行相同的操作。

例如,我可以显示所有海报,但如果我只想访问一张海报或一部特定电影(如 id)中的任何值,我会得到:

未捕获类型错误:无法读取未定义的属性(读取“id”)

我在控制台中注意到,当我登录

movieList[1]
时,它运行了 4 次。两次返回未定义,然后两次返回对象。

电影反应组件

import React, { useEffect, useState } from 'react';
import tmdb from '../api/tmdb';

function Movie() {

    const [movieList, setMovieList] = useState([])
    
    useEffect(() => {
      const getMovieList = async () => {
        const {data} = await tmdb.get('/discover/movie?')
        setMovieList(data.results)
      }
      getMovieList()
    },[])

    console.log(movieList) // this works
    console.log(movieList[1]) // this works
    console.log(movieList[1].id) // this returns "Uncaught TypeError: Cannot read properties of undefined (reading 'id')"

  return (
    <div>

        {/* this works and renders a list of posters */}

        {movieList.map((movie) => (
          <img alt={""} style={{width:"300px", marginLeft:"10px", marginTop:"10px"}} src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}/>
          ))}


        {/* this returns 'Uncaught TypeError: Cannot read properties of undefined (reading 'id')' */}

        <img alt={""} style={{width:"300px", marginLeft:"10px", marginTop:"10px"}} src={`https://image.tmdb.org/t/p/w500${movieList[1].poster_path}`}/>
    </div>
  )
}


export default Movie

获取组件:

import axios from 'axios';

export default axios.create({
    baseURL: 'http://api.themoviedb.org/3',
    headers: {
        accept: "application/json"
    },
    params: {
        api_key:'key here'
    }
})

电影对象示例

{
    "adult": false,
    "backdrop_path": "/rMvPXy8PUjj1o8o1pzgQbdNCsvj.jpg",
    "genre_ids": [
        28,
        12,
        53
    ],
    "id": 299054,
    "original_language": "en",
    "original_title": "Expend4bles",
    "overview": "Armed with every weapon they can get their hands on and the skills to use them, The Expendables are the world’s last line of defense and the team that gets called when all other options are off the table. But new team members with new styles and tactics are going to give “new blood” a whole new meaning.",
    "popularity": 1489.424,
    "poster_path": "/mOX5O6JjCUWtlYp5D8wajuQRVgy.jpg",
    "release_date": "2023-09-15",
    "title": "Expend4bles",
    "video": false,
    "vote_average": 6.3,
    "vote_count": 254
}
javascript reactjs object undefined
1个回答
0
投票

movieList
最初是一个空数组:

const [movieList, setMovieList] = useState([])

所以你在这里做的是:

console.log(movieList) // logging an empty array
console.log(movieList[1]) // logging the second element in an empty array, which is "undefined"
console.log(movieList[1].id) // trying to log the id property from that "undefined" element

由于

undefined
没有属性,因此会产生错误。

最简单的是,您可以完全删除这些

console.log
语句。但如果您想保留它们用于调试目的,则需要考虑空数组。例如,您可以使用可选链接:

console.log(movieList);
console.log(movieList[1]);
console.log(movieList[1]?.id);

或者也许根据数组的长度将一些内容包装在条件中:

console.log(movieList);
if (movieList.length > 1) {
  console.log(movieList[1]);
  console.log(movieList[1].id);
}

对于 JSX 标记,只需删除

<img>
操作之外的
.map()
即可。您已经在
.map()
操作内显示了数组中每个元素的所有值,我认为无需在其外部显示一个特定的值。但如果您出于某种原因确实想要这样做,则必须先检查数组是否有任何元素。

但总的来说,要点是您无法记录具有零个元素的数组中的第二个元素(或任何元素)的属性。

© www.soinside.com 2019 - 2024. All rights reserved.