如何拆解嵌套道具?

2022-03-02 00:00:00 reactjs javascript jsx

我开始学习Reaction js,然后我谈到了破坏道具这个话题。通常,我们要做的是分解道具,然后使用属性,就像问候组件中的以下代码

import React from "react";
const Greet = props => {
  const { name, heroName } = props; //here I destructured it
  return (
    <div>
      <h1>
        Hello {name} a.k.a {heroName}
      </h1>{" "}
      // and then use simply name and heroName
    </div>
  );
};
export default Greet;

这是我的App组件

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import Greet from "./components/Greet";
function App() {
  return (
    <div className="App">
      <Greet name="kaptan" heroName=" ek" />
    </div>
  );
}
export default App;

上面的代码运行良好,然后我进一步创建了一个人,下面的一个NameList组件就是我的NameList组件

import React from "react";
import Person from "./Person";
function NameList() {
  const persons = [
    {
      id: 1,
      name: "kaptan",
      age: 30,
      skill: "react"
    },
    {
      id: 2,
      name: "rinku",
      age: 29,
      skill: "java"
    },
    {
      id: 3,
      name: "ankit",
      age: 39,
      skill: "vue"
    }
  ];
  const personsList = persons.map(person => <Person person={person} />);
  return <div>{personsList}</div>;
}
export default NameList;

这是我的Person组件

import React from "react";
const Person = ({ person }) => {
  // here i need to destructure person object
  return (
    <div>
      <h2>
        I am {person.name},My age is {person.age},I know {person.skill}
      </h2>
    </div>
  );
};
export default Person;

所以我的问题是,为什么我本人的组件不能像我在Greet组件中所做的那样进行分解

这样

import React from "react";
const Person = props => {
  const { name, age, skill } = props;
  return (
    <div>
      <h2>
        I am {name},My age is {age},I know {skill}
      </h2>
    </div>
  );
};
export default Person;

它没有给我正确的输出为什么?


解决方案

可以使用nested destructuring获取person属性:

const { person: { name, age, skill } } = props;

这里使用嵌套析构是因为props有这样的结构:

{
  person: {
    name: ...,
    age: ...,
    skill: ...
  }
}

或者,您也可以只从props获取person,然后使用其属性,类似于您最初编写的内容:

const { person } = props;

return (
  <div>
     <h2>I am {person.name},My age is {person.age},I know {person.skill} </h2>
  </div>
);

相关文章