简体   繁体   English

反应:当使用 axios 将 api 数据传递给子组件时,如何解决未定义的问题?

[英]React: How do I fix getting undefined when passing api data to child component using axios?

I'm having problems accessing data that I pass it to a child component.我在访问将其传递给子组件的数据时遇到问题。 This may have to do with the Promise not being resolved at the time of accessing it but that's what I don't know how to fix.这可能与 Promise 在访问时未解决有关,但这就是我不知道如何解决的问题。 What I need is to make sure the data is fully retrieved from the parent and then passed to the child component ApplicationStats.我需要的是确保从父组件中完全检索数据,然后将其传递给子组件 ApplicationStats。

This is the code I wrote for the parent component:这是我为父组件编写的代码:

import axios from 'axios';
import ApplicationStats from './ApplicationStats';

const Apps = () => {
  const [apiData, setApiData] = useState([]);
  const ifaUrl= 'url1';
  const orgUrl = 'url2';

  const fetchData = () => {
    const ifaResponse = axios.get(ifaUrl);
    const orgResponse = axios.get(orgUrl);
    axios.all([ifaReq, orgReq]).then(
      axios.spread((...responses) => {
        setApiData({
          ifaResult: responses[0];
          orgResult: responses[1];
        });
      }),
    );
  };

  useEffect(() => {
    fetchData();
  }, [])

  return (
    <div className="card-deck"
      <ApplicationStats apiData={apiData} />
    </div>
  );
};

This is the child component:这是子组件:

import React from 'react';

const ApplicationStats = ({apiData}) => {
  const {ifaResult, orgResult} = apiData;
  console.log(ifaResult.data);

  return (
    <div>Hey</div>
  );
};

In the child component, if I replace console.log(ifaResult.data) with console.log(ifaResult) , I get this undefined and then I get the data.在子组件中,如果我用console.log(ifaResult.data)替换 console.log console.log(ifaResult) ,我得到这个 undefined 然后我得到数据。

不明确的

What I'm trying to do is to keep my console.log(ifaResult.data) in the child component, but I get this我想要做的是将我的console.log(ifaResult.data)保留在子组件中,但我明白了

错误

I've even tried using async/await, but I feel I'm missing something important.我什至尝试过使用 async/await,但我觉得我错过了一些重要的东西。

Your initial value for apiData is an empty array. apiData的初始值是一个空数组。

When the Ajax response arrives you replace it with an object that has a ifaResult property.当 Ajax 响应到达时,您将其替换为具有ifaResult属性的 object。

… but by then you've already rendered the component using the initial data and got the error. …但是到那时你已经使用初始数据渲染了组件并得到了错误。

——— ———

When you set the initial data for the state, make it the same shape as the data you intend to put in it later.当您为 state 设置初始数据时,使其形状与您稍后打算放入的数据相同。

The issue is that you're initializing apiData as an array, rather than an object.问题是您将apiData初始化为数组,而不是 object。 Here's the issue, demonstrated:这是问题,证明:

let x = [];
const { property } = x; // property === undefined!
console.log(property.data) // ERROR! Cannot find property `data` of undefined

The reason this breaks is because when Javascript checks an object for a property that doesn't exist, it returns undefined.这中断的原因是,当 Javascript 检查 object 中不存在的属性时,它返回未定义。 However, when you check for a property off of undefined , JavaScript will throw an error.但是,当您检查undefined的属性时, JavaScript 将引发错误。

This will prevent you from getting the error, and will log undefined to the console instead of breaking:这将防止您收到错误,并将undefined记录到控制台而不是中断:

const [apiData, setApiData] = useState({ ifaResult: {}, orgResult: {}});

Another Contrived Example:另一个人为的例子:

const x = undefined;
x.data // ERROR!

//...

const x = {}
x.data // undefined

暂无
暂无

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

相关问题 在React.js的父组件中使用react-router时,如何使用react context API将数据从父组件传递到子组件? - How do I use react context API to pass data from parent component to child component when using react-router in the parent component in React.js? 使用 Axios 客户端将数据向下传递到子组件时出错 - Getting an error while passing the data using Axios client down to the child component 如何确保 axios 获取响应仅执行一次并且在将数据传递给子组件时可以访问? - How can I ensure that the axios get response is only executed once as well as accessible when passing data to child component? 将 axios 响应传递给反应中的子组件 - passing axios response to child component in react 使用 React Hooks,当我将 prop 从父组件传递给子组件时,子组件中的 prop 未定义 - Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined 当我加载 api 请求并且我的反应组件尝试呈现时,我总是收到数据未定义错误 - I am always getting a data is undefined error when I am loading a api request and my react component trys to render 如何将更新数据发送到子组件。 反应 - How do I send updating data to a child component. React 为 API 使用迭代器但得到“未定义”,如何解决? - Using iterator for an API but getting 'undefined',How to fix it? React Native 错误:将数据传递给组件时,未定义不是 object - React Native Error: undefined is not an object when passing data to component 通过数据传递<link>但是在 React 中使用 React Router 变得未定义 - Passing data through <Link /> but getting undefined using React Router in React
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM