不知道为什么在将对象数组作为 props 传递给 React JS 中的子组件时 IM 出现错误



我想将一个数组作为道具传递给子组件,并尝试使用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;

简短回答-您得到的错误消息是绝对正确的。如果你阅读了React文档,你的JSX会编译成React.createElement(component,props,…children(。yes对象不能是children。参考-https://reactjs.org/docs/jsx-in-depth.html#children-在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中,它将抛出一个错误(注释代码(。此外,请检查表组件(如果是第三方库(,它期望的数据格式。如果它是您的,那么您必须使用Object.entries()Object.keys()Object.values()迭代对象以显示数据

希望这能回答你的问题。如果你觉得有帮助,请投赞成票。

最新更新