Reactjs 如何在React中调用对象数组中的变量名

Reactjs 如何在React中调用对象数组中的变量名,reactjs,typescript,Reactjs,Typescript,这是我在react中的代码 const [value, setValue] = React.useState<CountriesEntityData | null>({ id: '', name: '', regions: [ { id: '', name: '', districts: [ { id: '', name: '',

这是我在react中的代码

 const [value, setValue] = React.useState<CountriesEntityData | null>({
    id: '',
    name: '',
    regions: [
      {
        id: '',
        name: '',
        districts: [
          {
            id: '',
            name: '',
            locations: [{ id: '', city: '', division: '', street: '' }],
          },
        ],
      },
    ],
  })

有谁能给我一个处理这种情况的教程链接吗?谢谢。

如果你只想使用第一个元素,你可以做:

let name = value?.regions?.[0]?.name;
如果你想根据id搜索对象,那么我认为数组中有一个find函数,你可以这样使用:

let name = value?.regions?.find((elm) => elm.id == 'myId')?.name;

值中的
区域
数组

而不是回答
value?.regions?.name


由于
区域
包含
对象
对象
包含属性“name”

用于此类问题,只需使用
日志
并在控制台中查看变量即可

  console.log(your const);
然后,通过查看控制台,您可以很容易地看到如何寻址阵列以获得所需的结果

现在假设要提取对象中的嵌套名称, 对于彼此内部的两个数组,应该使用两个嵌套的
MAP
。 这可以给你一个想法:

{ListOfData.map((item, index) => (
  <div key={index}>
    <h1>{item.title}</h1>
    {item.content.map((c, i) => (
      <div key={i}>
        <h3>{c.title}</h3>
        <h3>{c.description}</h3>
        <hr />
      </div>
    ))}
  </div>
))}
{ListOfData.map((项目,索引)=>(
{item.title}
{item.content.map((c,i)=>(
{c.title}
{c.description}

))} ))}
您能详细说明一下吗?哪个变量名?你想在哪里使用它?你想在定义状态的时候使用变量还是什么?为什么要编写此代码
value?.regions?.name
?您希望实际调用
setValue(null)
?如果没有,并且使用初始值,为什么还要允许
null
CountriesEntityData | null
)?这只会让事情变得更复杂。
{ListOfData.map((item, index) => (
  <div key={index}>
    <h1>{item.title}</h1>
    {item.content.map((c, i) => (
      <div key={i}>
        <h3>{c.title}</h3>
        <h3>{c.description}</h3>
        <hr />
      </div>
    ))}
  </div>
))}