【问题标题】:don't know why im getting error while passing array of objects as props to child component in react js不知道为什么在将对象数组作为道具传递给反应 js 中的子组件时出现错误
【发布时间】:2022-01-11 04:02:41
【问题描述】:

我想将一个数组作为道具传递给子组件,并尝试使用 react table 使用该道具创建表。

将数组作为道具传递给表格组件时,我收到此错误消息。

Objects are not valid as a React child (found: object with keys {continent, country, totalcases, criticalcases, activecases, deaths, recovery, newcases, death1mpop, cases1mpop}). If you meant to render a collection of children, use an array instead.      

应用组件:

function App() {
  const [totalCases, setTotalCases] = useState({});
  const [countryData, setCountryData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [loadingCountry, setLoadingCountry] = useState(true);

  const getCovidData = async () => {
    setLoading(true);
    const res = await fetch(
      "https://covid-193.p.rapidapi.com/statistics?country=all",
      {
        method: "GET",
        headers: {
          "x-rapidapi-host": "covid-193.p.rapidapi.com",
          "x-rapidapi-key":
            "xxxxxxxxxxxxxxxxxxxxxxxxx",
        },
      }
    );
    const data = await res.json();
    const actualData = data.response[0];
    setTotalCases(actualData);
    setLoading(false);
    // console.log(actualData);
  };

  const getCountriesData = async () => {
    setLoadingCountry(true);
    const res = await fetch("https://covid-193.p.rapidapi.com/statistics", {
      method: "GET",
      headers: {
        "x-rapidapi-host": "covid-193.p.rapidapi.com",
        "x-rapidapi-key": "xxxxxxxxxxxxxxxxxxxxxxxxx",
      },
    });
    const data = await res.json();
    console.log(data.response);
    let requiredData = data.response.map((d) => {
      return {
        continent: d.continent,
        country: d.country,
        totalcases: d.cases.total,
        criticalcases: d.cases.critical,
        activecases: d.cases.active,
        deaths: d.deaths.total,
        recovery: d.cases.recovered,
        newcases: d.cases.new,
        death1mpop: d.deaths["1M_POP"],
        cases1mpop: d.cases["1M_POP"],
      };
    });
    console.log(requiredData);
    setCountryData(requiredData);
    // setCountryData(data.response);
    setLoadingCountry(false);
    console.log(countryData);
    console.log(countryData.length);
  };

  useEffect(() => {
    getCovidData();
    getCountriesData();
  }, []);

  return (
    <div className="App">
      <h1>Covid Tracker....</h1>
      {loading ? <h1>Loading data</h1> : <Details totalCases={totalCases} />}
      {/* {loadingCountry ? <h1>Loading list</h1>
        :
          <Table countryData={countryData}/>
      } */}
      {/* {countryData !== undefined && <Table countryData={countryData}/>} */}
    </div>
  );
}
export default App;

【问题讨论】:

  • 您检查过typeof requiredData 吗?映射data.response 后,您将返回object
  • 因为它是数组,所以数据类型将是对象。当我用 Array.isArray 检查它时,它返回 true
  • 你能把你的表格组件包括进来吗?
  • 您可以添加响应吗?看起来它是您传递的父对象。
  • Table 组件应该是问题的根源。它可能试图将countryData 渲染为对象而不是反应元素。

标签: javascript reactjs react-native fetch-api


【解决方案1】:

简答 - 您收到的错误消息是绝对正确的。如果您阅读 React 文档,您的 JSX 将编译为 React.createElement(component, props, ...children)。是的,对象不能是孩子。参考 - https://reactjs.org/docs/jsx-in-depth.html#children-in-jsx

由于我没有您的示例数据,我假设您的数据可能是这样的:

<Test arr={[{ a: 1 }, { b: 2 }, { c: 3 }]} />

我正在创建一个小组件来呈现这些数据:

import React from "react"

function Test(props) {
  return (
    <div>
      {props.arr.map((x, index) => {
        console.log(index, x);
        // return <h1 key={index}>{x}</h1>;
        return <h1 key={index}>{Object.keys(x).map((y) => x[y])}</h1>;
      })}
    </div>
  );
}

如果我在 JSX 中放置对象,它会抛出一个错误(注释代码)。 另请检查 Table 组件(如果它是第 3 方库),它期望数据的格式。如果它是你的,那么你必须使用 Object.entries()Object.keys()Object.values() 遍历对象以显示数据

希望这能回答您的问题。如果觉得有帮助,请点赞。

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多