Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - React: Map over Array of Obects (fake data) to render an Array of words

I'm able to display the content from spellingListData object. It is displaying all the words in one h1 tag. That is not what I'm needing right now.

If I turn spellingListData into one Array with all the words, then I'm able to map and create multiple h1 tags for each item in the array. That is what I"m wanting - assign each word with an h1 tag.

What am I missing? I've been stuck on this one. How do I drill down into the object's array? I've tried word[0].spellingwords which didn't work?

Data Component:

    import React from "react";
import { useState } from "react";
import WordList from "./WordList";
 
function Data(props) {
  const [words, setWords] = useState(spellingListData);
  return (
    <div>
      <WordList words={words} />
    </div>
  );
}
// Simulated Data
const spellingListData = [
  {
    id: 1,
    spellingWords: ["careful", "stared", "shared", "pair", "stairs", "wear", "bear", "where", "there", "dear", "rear", "gear", "here", "career", "peer", "shore", "carve", "storm"],
  },
  {
    id: 2,
    bonusWords: ["January", "parable"],
  },
];
 
export default Data;

WordList Component:

      import React from "react";
 
function WordList({ words }) {
  return (
    <div>
      {
        words.map((word) => {
          return <h1 key={word.id}>{word.spellingWords}</h1>;
        })
      }
    </div>
  );
}
 
export default WordList;
question from:https://stackoverflow.com/questions/65862953/react-map-over-array-of-obects-fake-data-to-render-an-array-of-words

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

1 Answer

0 votes
by (71.8m points)

You should map on the spellingWords array:

function WordList({ words }) {
 return (
   <div>
     {
       words[0].spellingWords.map( word =>
          (<h1 key={word}>{word}</h1>)
        )
     }
   </div>
 );
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...