【发布时间】:2021-11-14 21:14:26
【问题描述】:
我有companies.json,我正在尝试从中获取数据,然后将公司名称显示为复选框,所以这是我的父组件:
import React, { useEffect, useState } from "react";
import SimpleBox from "../components/sub-components/SimpleBox";
import BoxWithSearch from "../components/sub-components/BoxWithSearch";
import { useDispatch, useSelector } from "react-redux";
import { listProducts } from "../actions/productActions";
import { listCompanies } from "../actions/companyActions";
export default function HomeScreen() {
const dispatch = useDispatch();
const companyList = useSelector((state) => state.companyList);
const { companies } = companyList;
useEffect(() => {
dispatch(listCompanies());
}, [dispatch]);
return (
<div className="container">
<div className="row">
<div className="col-lg-3 col-md-12 col-sm-12 col-xs-12">
<h3 className="title">Brands</h3>
{companies.map((company) => (
<BoxWithSearch type={"companies"} company={company} />
))}
</div>
</div>
</div>
);
}
BoxWithSearch 组件之后:
import React from "react";
import CheckBox from "../custom-components/CheckBox";
export default function BoxWithSearch(props) {
return (
<div className="search-w-box card">
<div className="card-header">
<input type="text" className="form-control" placeholder={`Search ${props.type}`} aria-label="Recipient's username"></input>
</div>
<div className="card-body">
<CheckBox text={props.name} />
</div>
</div>
);
}
这里是复选框:
import React from "react";
export default function CheckBox(props) {
const [isChecked, setChecked] = React.useState(false);
const toggleCheck = (e) => {
setChecked(e.target.checked || !isChecked);
};
return (
<>
<label className="checkbox-container">
{props.text}
<input
type="checkbox"
checked={isChecked}
onChange={(e) => toggleCheck(e)}
id={props.id}
/>
<span className="checkmark"></span>
</label>
</>
);
}
但不幸的是,我得到了:
Uncaught TypeError: Cannot read properties of undefined (reading 'map') error and I have no idea why and it is getting me crazy.
你能看一下吗?而我的 JSON 数组是这样的:
[
{
"slug": "Dickens-Franecki",
"name": "Dickens - Franecki",
"address": "12158 Randall Port",
"city": "East Maureenbury",
"state": "NE",
"zip": "74529",
"account": 31010023,
"contact": "Lonzo Stracke"
},
{
"slug": "Weissnat-Schowalter-and-Koelpin",
"name": "Weissnat, Schowalter and Koelpin",
"address": "92027 Murphy Cove",
"city": "Port Malachi",
"state": "WY",
"zip": "56670-0684",
"account": 81813543,
"contact": "Kathryne Ernser"
},
]
【问题讨论】:
-
使用可选更改
companies?.map。 -
什么是可选更改? @Asifvora
-
取决于您的状态配置,在 listCompanies 操作完成之前,可以未定义公司。这导致您的company.map 无法调用。要修复它,只需将 Companies.map 替换为 (companies || []).map。
-
你能展示你的减速机吗?理想情况下,我会在 companyList 减速器中设置一个初始值,就像这样。
const INITIAL_STATE = { companies:[] }这将解决您的问题。因为当应用程序挂载时,有一段时间没有公司属性,所以你需要有一个初始状态 -
可选的链接运算符 (?.) 使您能够读取位于连接对象链深处的属性的值,而无需检查链中的每个引用是否有效。常量冒险家 = { 名称:“爱丽丝”,猫:{ 名称:“黛娜”} }; const dogName = Adventurer.dog?.name; console.log(dogName); developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: reactjs axios fetch fetch-api react-component