【发布时间】:2022-07-13 21:15:31
【问题描述】:
我在名为clickedCountry 的变量中有一个对象,其结构为{name:x, population: x, region:x, capital: x...}。我可以通过clickedCountry.population 访问它。但是,如果我想以编程方式访问它(我写的地方,不起作用)我得到
对象作为 React 子对象无效
{
['Name', 'Population', 'Region','Capital', 'Currencies', 'Languages'].map(el => {
let name = el.toLowerCase()
console.log(typeof(name)) //=>returns string
console.log(name) //=> returns population, region etc.
return (
<Typography gutterBottom component="div">
<span className='font-600'>{el}:</span>
{clickedCountry.name} //=> works
{clickedCountry[name]} //=> works not
{clickedCountry[`${name}`]} //=>works not
{clickedCountry[`${el.toLowerCase()}`]} //=>works not
</Typography>
)
});
}
【问题讨论】:
-
你试过
clickedCountry["Name"]吗? -
你只是从
map返回。你没有从组件返回任何东西(如果那是一个组件 - 你缺少一些代码)。 -
检查数组中字符串的大小写。我们可以看看你的对象吗?您说“{clickedCountry.name} //=> 有效”,但在返回中您正在寻找 clickedCountry.Name
标签: javascript reactjs