Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

javascript - How to show a nested list in React.js?

I have three arrays persons, skills and personSkills. Now I want to show all skills for each person in a unordered vertical list, like this

  • Person1
    - Skill1
    - Skill2
  • Person2
    - Skill3
    - Skill4

Here's my code-

let persons = ["Person1", "Person2"];
let skills = ["Skill1", "Skill2", "Skill3", "Skill4"];

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      personSkills: [
        { Person1: ["Skill1", "Skill2"] },
        { Person2: ["Skill3", "Skill4"] }
      ]
    };
  }

  render() {
    return (
      <div className="App">
        {persons.map((eachP) => (
          <ul>
            {eachP}

            {this.state.personSkills.map((eachPS) => {
              eachPS[eachP] && eachPS[eachP].map((eachS) => <li>{eachS}</li>);
            })}
          </ul>
        ))}
      </div>
    );
  }
}

But it just shows

  • Person1

  • Person2

Here's a link to my sandbox - sandbox

Please help.

question from:https://stackoverflow.com/questions/65942160/how-to-show-a-nested-list-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could simplify the way you store the skills as follows:

this.state = {
      personSkills: {
        Person1: ["Skill1", "Skill2"],
        Person2: ["Skill3", "Skill4"]
      }
};

Now while rendering:

render() {
    return (
      <div className="App">
        {persons.map((eachP) => (
          <ul>
            {eachP}
            {this.state.personSkills[eachP] && this.state.personSkills[eachP].map((skill) => {
              return <li>{skill}</li>;
            })}
          </ul>
        ))}
      </div>
    );
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...