简体   繁体   English

无法通过 ReactJS 中的道具访问 object 属性

[英]Cannot access object properties via props in ReactJS

I fetch data from API and pass it to Table component like this:我从 API 获取数据并将其传递给 Table 组件,如下所示:

function MainSectionOrganization() {

    const [obj, setObj] = useState([]);

    useEffect(() => {
        fetch('http://127.0.0.1:5000/getCompanies')
        .then((response) => {
            return response.json();
        }).then((data) => {
            setObj(data);
        })
    }, []);

    return (
        <Table data={obj} />
    )
}

Then, in Table component, I try to do console.log for props.data[0] and I see data in Chrome terminal correctly.然后,在 Table 组件中,我尝试为 props.data[0] 执行 console.log,并且我在 Chrome 终端中正确看到了数据。

import React from 'react';
import './Table.css';
import { useTable } from 'react-table';

function Table(props) {

    console.log(props.data[0]);
    ...

在此处输入图像描述

However, when I try to access any properties of the object, for example console.log(props.data[0].OU01_Code ), I encounter an error Cannot read property '...' of undefined但是,当我尝试访问 object 的任何属性时,例如console.log(props.data[0].OU01_Code ),我遇到一个错误Cannot read property '...' of undefined

I see many people have solution with class component, but for some reason I need to use function component.我看到很多人都有使用 class 组件的解决方案,但由于某种原因,我需要使用 function 组件。 Can you help me on this one?你能帮我解决这个问题吗?

Hey the problem is that you trying to access props.data[0].OU01_Code and it is not there YET, so you need to make some kind of condition to check that it is there.嘿,问题是您尝试访问props.data[0].OU01_Code并且它还不存在,因此您需要做出某种条件来检查它是否存在。 Try:尝试:

if (props.data && props.data[0]) {
  console.log(props.data[0].OU01_Code)
}

Let me know if it helps, cheers让我知道是否有帮助,干杯

fetch is asynchronous. fetch是异步的。 So the first thing the component does is get rendered with an empty array:所以组件做的第一件事就是用一个空数组渲染:

const [obj, setObj] = useState([]);
//...
return (
    <Table data={obj} />
)

When that happens, any reference to an element of that array would be undefined :发生这种情况时,对该数组元素的任何引用都将是undefined

props.data[0]

So trying to read a property of that undefined array element would result in that exact error:因此,尝试读取该未定义数组元素的属性将导致该确切错误:

props.data[0].OU01_Code
// Cannot read property 'OU01_Code' of undefined

After fetch resolves its result and the state is updated, obj has elements (presumably) and you can access them.fetch解析其结果并更新 state 后, obj具有元素(大概)并且您可以访问它们。


Conceptually, you need to handle the situation where your array is empty.从概念上讲,您需要处理数组为空的情况。 Do you want to display <Table /> at all in that case?在那种情况下你想显示<Table />吗? If not, you can conditionally display it in the parent component:如果没有,可以有条件地在父组件中显示:

return (
    <>
        {obj.length > 0 && <Table data={obj} />}
    </>
)

Or if you do want to display <Table /> with an empty array then you'll need to include logic within that component (which we can't see at this time) to handle an empty array.或者,如果您确实想用空数组显示<Table /> ,那么您需要在该组件中包含逻辑(我们目前无法看到)来处理空数组。 Basically, you need to check props.data.length before trying to access props.data[0] .基本上,您需要在尝试访问props.data[0]之前检查props.data.length

because the initial render will occur before the API call is completed you can use props.data && console.log(props.data[0]) or if you're open to use Optional chaining it would be easy even props?.data?.[0]因为初始渲染将在 API 调用完成之前发生,您可以使用props.data && console.log(props.data[0])或者如果您愿意使用可选链接,即使props?.data?.[0]

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

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