【问题标题】:Accessing array of objects assigned as a constant within an object and mapping its values访问在对象中分配为常量的对象数组并映射其值
【发布时间】:2021-08-23 08:52:23
【问题描述】:

/*如果我需要一个数组来映射类型的值,如下面的数据(戏剧/喜剧/科学),使用 map 函数,如何访问它。我的代码抛出错误。在 React JS 中编码/

我确实实现了直接在对象中使用对象数组定义数据结构的结果。但是为什么使用此代码无法访问数组进行映射。

const drama = [
    {name: "So {Long, My Son",
    rating: "5/5"},
    {name: "Schindlers List",
    rating: "4.5/5"},
  ]
 const comedy = [{
    name: "Snatch",
    rating: "4/5"},
    {name: "Two Barrels",
    rating: "4/5"}
  ];
  const science = [
    {name: "Interstellar",
    rating: "4/5"},
    {name: "ET",
    rating: "4/5"}
  ];
    const movies = {     /** Can I even define like this*/
    "Drama" : drama,
    "Comedy": comedy,
    "Science": science
    }; 



var [genreSelect, setgenreSelect] = useState("");
var movieList = Object.keys(movies);
  
  function clickHandler(x) {
    setgenreSelect(x);
  }

  return (
    <div className="App">
      <div class="container">
        <h1>My Movie List</h1>
        <h3> Hit on the genres to check out my favourite movies</h3>
      </div>
      <nav class="navDiv">
        {movieList.map((genre)=>{
          return(
            <button class="btn" onClick={() => clickHandler(genre)}>{genre}</button>
          );        
        })}
      </nav>
      <ul class="list-nonbullet">

**/**-->> The part down  below throws an error. I have tried to access object[property] the value being an array defined */**

        {movies["genreSelect"].map((movie)=>(   
          <li class="listDiv">
            <div>{movie.name}</div>
            <div>{movie.rating}</div>
        </li> 
        ))}        
      </ul>
    </div>
  );
}

【问题讨论】:

  • How do I ask a good question?: " 告诉其他读者错误信息的确切措辞是什么,是哪一行代码产生的"
  • movies["genreSelect"].map(...) - movies 没有属性 "genreSelect"

标签: javascript reactjs dictionary object


【解决方案1】:

你为什么在这一行使用双引号 {movies["genreSelect"].map((movie)=>(

我猜应该是这样的 {movies[genreSelect].map((movie)=>(

【讨论】:

  • 我没有使用引号。我认识的大多数人告诉我它不起作用,因为 map 函数仅适用于数组。但是我不明白为什么这没有返回一个数组。
  • const selectedMovies = movies[genreSelect];尝试映射 selectedMovies。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 2016-09-13
  • 2019-04-28
  • 2020-06-17
  • 2017-08-23
相关资源
最近更新 更多