如何获取数据并将其显示在孙子组件中

How to fetch data and display it in grandchild component

我有一个父组件,我在这里获取数据:

import React, { useEffect, useState } from "react";
import BoxWithSearch from "../components/sub-components/BoxWithSearch";
import { useDispatch, useSelector } from "react-redux";
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>
              <BoxWithSearch type={"companies"} companies={companies} 
        </div>
        
      </div>
    </div>
  );
}

所以公司是这样来的: [

  {
    "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"
  },
]

我试图将这些公司显示为复选框,但 HomeScreen 的子组件是 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">
        {this.props && this.props.map((prop) => <CheckBox text={prop.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>
    </>
  );
}

但不幸的是,我遇到了未捕获的类型错误:无法读取未定义的属性(读取 'props'),我真的很困惑,不知道该怎么办。

你能看看吗? 谢谢...

因为你传递的道具是这样的:<BoxWithSearch type={"companies"} companies={companies} />,你应该期望在你的 BoxWithSearch 组件中有一个 props 具有属性 typecompanies。因此,在 BoxWithSearch 中,您可以像这样映射公司 属性:

props.companies.map((prop) => <CheckBox text={prop.name} />

请注意,这里您只是将 text 属性 传递给 CheckBox,但在您的代码中您也在寻找 id。所以我想你应该有这样的东西:

props.companies.map((prop) => <CheckBox text={prop.name} id={prop.id} />