简体   繁体   English

无法使用 React 钩子访问获取的 Json 数据的 object 属性

[英]Cannot access object properties of fetched Json data with React hooks

I can't access the data object properties in the parent component我无法访问父组件中的data object 属性

After I fetch the data from the api in the child function, I receive a json data.从子 function 中的 api 获取数据后,我收到json数据。 Within the .then promise if I console log the response I get [object Object] ..then promise 中,如果我控制台记录我得到的响应[object Object] If I console log response.page or response.results[1].title I get the expected object property, but log of response.results gives [object Object] [object Object] .如果我控制台日志response.pageresponse.results[1].title我得到预期的 object 属性,但response.results的日志给出[object Object] [object Object]

Also I need the data in the parent component, so I put that data in fetchedData state hook, and returned it.我还需要父组件中的数据,所以我将这些数据放在 fetchedData state 挂钩中,然后返回。 So inside the parent component if I console log the data from the function.因此,如果我控制台记录来自 function 的数据,则在父组件内部。 I get as [object Object] .我得到[object Object] And if I do maindData.data or mainData.data.page , I get an error saying data or page of undefined is not accessible unlike in the previous case where at least I was getting the property.如果我执行maindData.datamainData.data.page ,我会收到一条错误消息,指出无法访问未定义的数据或页面,这与至少我获得该属性的前一种情况不同。

What could be the cause of this error?此错误的原因可能是什么? Is it because react hooks always returns an Array rather than an object?是因为反应钩子总是返回一个数组而不是一个 object? If so than what could be the solution for this??如果是这样,那么解决方案可能是什么?


Parent component父组件

import React, {useEffect, useState} from 'react';
import axios from "axios"
import {useParams} from 'react-router-dom'
import TmdbApiUrl from "./apiUrl"
import {FetchUrl} from "./fetchUrl"
import "../assets/mediaList.sass"
import Navigation from "./partials/nav";
import MediaCard from "./partials/mediaCard";


const MediaList = ()=> {
   const {generalType} = useParams();
   const {media} = useParams();
   const {page} = useParams();
   const key=process.env.API_KEY;
   const url=`${TmdbApiUrl.baseURL()}${media}/${generalType}?api_key=${key}&page=${page}`;
   const {mainData,loading,status}=FetchUrl(url);

  console.log(`#loading==>${loading}`);
  console.log(`#FetchedData==>${mainData.data}`);
  console.log(`#status==>${status}`);

  return (
    <div className="mediaList">
      <Navigation />
      <div className="list m-5 d-flex flex-wrap justify-content-around">
        <MediaCard/>
        {/*{data.map(media=>(*/}
        {/*<div className="m-5">*/}
        {/*  <MediaCard*/}
        {/*      rating={true}*/}
        {/*      ratingValue={media.vote_average}*/}
        {/*      year={media.release_date}*/}
        {/*      title={media.title}*/}
        {/*      text={media.overview}/>*/}
        {/*</div>))}*/}
      </div>
    </div>
  );
};
export default MediaList

Child function儿童 function

import {useEffect, useState} from 'react';
import axios from "axios";

export const FetchUrl=(url)=> {
  const [fetchedData,setFetchedData]=useState({mainData:null,loading:true,status:null});
  console.log(`url==>${url}`);
  useEffect(()=>{
    setFetchedData({mainData:null,loading:true,status:null});
    axios
      .get(url)
      .then(response=>{
        console.log(`response==> ${response}`);
        setFetchedData({mainData:response.data,loading: false,status:response.status});
        })
      .catch((error)=> console.log(`sorry for the ${error}`));
  },[url]);
  return fetchedData;
};

JSON data from TMDB API JSON 数据来自 TMDB API

{
data:{
  "page": 1,
  "total_results": 10000,
  "total_pages": 500,
  "results": [
    {
      "popularity": 564.69,
      "vote_count": 2822,
      "video": false,
      "poster_path": "/xBHvZcjRiWyobQ9kxBhO6B2dtRI.jpg",
      "id": 419704,
      "adult": false,
      "backdrop_path": "/5BwqwxMEjeFtdknRV792Svo0K1v.jpg",
      "original_language": "en",
      "original_title": "Ad Astra",
      "genre_ids": [
        18,
        878
      ],
      "title": "Ad Astra",
      "vote_average": 5.9,
      "overview": "(description..bla..bla..bla...)",
      "release_date": "2019-09-17"
    },
    {
      "popularity": 194.755,
      "vote_count": 12119,
      "video": false,
      "poster_path": "/5vHssUeVe25bMrof1HyaPyWgaP.jpg",
      "id": 245891,
      "adult": false,
      "backdrop_path": "/lvjRFFyNLdaMWIMYQvoebeO1JlF.jpg",
      "original_language": "en",
      "original_title": "John Wick",
      "genre_ids": [
        28,
        53
      ],
      "title": "John Wick",
      "vote_average": 7.2,
      "overview": "(description..bla..bla..bla...)",
      "release_date": "2014-10-22"
    }
  ]
},
  status:200
}


Found a solution but using redux.找到了解决方案,但使用 redux。 See if the json data fetched was huge ie deeply nested say for example查看获取的 json 数据是否巨大,例如,深度嵌套

API object=A:{
             B:{ 
               C:{ 
                 D:E }
                 }
               }

then I would have had to put if statements for each of the deeper object keys ie那么我将不得不为每个更深的 object 键添加 if 语句,即

received data=A.B.(C?C:null).(D?D:null)

or else it would give me C or D as undefined and this is not an efficient solution.否则它会给我 C 或 D undefined ,这不是一个有效的解决方案。 So then I used mapDispatchToProps & mapStateToProps from redux which dispatched the fetchAPI action and loaded the entire data before putting it into redux state.然后我使用了 redux 中的mapDispatchToPropsmapStateToProps ,它调度了 fetchAPI 操作并加载了整个数据,然后将其放入 redux Z9ED39E2EA931586B6A985A6942EF573E

You are setting data in wrong way您以错误的方式设置数据

setFetchedData({data:{mainData:response.data},loading: false,status:response.status});

should be应该

setFetchedData({ mainData:response.data ,loading: false, status:response.status });

Select the position of the object in the array and then access the property. Select position 的 object 在数组中然后访问属性。 Eg:例如:

User[0].name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM