【问题标题】:Objects are not valid as react child -react对象作为 react child -react 无效
【发布时间】: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


【解决方案1】:

您正在为数组中的每个元素返回有效的 JSX。 您还需要返回映射的数组。

你可能想这样做

{
return ['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>
    )

  });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2021-10-17
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多