![](/img/trans.png)
[英]TypeError: Cannot read properties of undefined, when trying to load MathJax to a div
[英]Getting "TypeError: Cannot read properties of undefined" when trying to access properties of an object
我有一个 function 从本地 JSON 文件中获取数据并呈现它。 简单的东西。 我在 useEffect 钩子中执行获取请求以仅在第一次渲染时触发它。 获取数据后,将其设置在employees
中。 在employees
中,我使用另一个 useEffect 来设置一些其他状态,其中包含来自employees
的数据。
const [employees, setEmployees] = useState<any>([]);
useEffect(() => {
fetch("data.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then(function (response) {
return response.json();
})
.then(function (data) {
setEmployees(data["employees"]);
});
}, []);
useEffect(() => {
console.log(employees)
/* set some other state */
}, [employees]);
/*render list of employees*/
我的问题是,我实际上无法访问employees
中的属性。 当我employees
的内容时,这就是我看到的,一个对象数组
[
{
"first_name": "John",
"last_name": "Doe",
},
{
"first_name": "Jane",
"last_name": "Doe",
}]
所以要访问 object 的属性,我试过这个
employees[0]["first_name"]
employees[0]."first_name"
employees[0][first_name]
employees[0].first_name
在前两个中,我收到此错误
TypeError: Cannot read properties of undefined (reading 'first_name')
在最后 2 个中,我收到此错误
Cannot find name 'first_name'
如果有人能告诉我如何正确访问我的数据,将不胜感激!
编辑:如果有任何改变,我正在 Typescript 工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.