【问题标题】:Getting data from an array in an array with ReactJS使用 ReactJS 从数组中的数组中获取数据
【发布时间】:2017-05-23 09:35:43
【问题描述】:

我对 ReactJS 很陌生,但我认为我正在取得一些进展......

认为我快到了,但我已经跌倒在我认为足够接近我的最后一个障碍的地方......这就是我想要实现的目标;

电视剧 - 辛普森一家

  • 姓名:巴特·辛普森,性别:男
  • 姓名:Homer Simpson,性别:男
  • 姓名:Ned Flanders,性别:男

电视节目 - 燧石

  • 姓名:Fred Flintstone,性别:男
  • 姓名:Barney Rubble,性别:男
  • 姓名:Wilma Flintstone,性别:女

我可以有数百个这样的,所以我不想只在两个 React 元素中构建这些 - 所以我已经组织了我很满意的数据;

var shows = [
{
  id: 1,
  show: 'Simpsons',
  characters: [
  { id: 1, name: 'Bart Simpson', gender: 'Male'},
  { id: 2, name: 'Homer Simpson', gender: 'Male'},
  { id: 3, name: 'Ned Flanders', gender: 'Male'}
]
},
{
  id: 2,
  show: 'Flintstones',
  characters: [
    { id: 1, name: 'Fred Flintstone', gender: 'Male'},
    { id: 2, name: 'Barney Rubble', gender: 'Male'},
    { id: 3, name: 'Wilma Flintstone', gender: 'Female'}
]
}
];

然后我用这样的表构建我的数据:

const ShowsTable = (props) => {
    return (
    <div>
      <h1>Show - {props.show}</h1>
      <table>
        <tr>
          <th>Name</th>
          <th>Gender</th>
        </tr>
        <tr>
          <td>XXX</td>
          <td>YYY</td>
        </tr>
      </table>
    </div>
  );
};

我有这个“工作”,我可以从主数组中获取节目名称和任何内容,但我无法从嵌套的“角色”子数组中获取数据

所以 XXX 和 YYY 是我想要获取姓名或性别数据的地方,在我看来,我应该能够做类似...

{props.characters}

或者也许得到嵌套元素,比如

{props.characters.props.name}

但我无法弄清楚这一点或找到任何文档 - 这是语法错误还是我错过了更基本的东西......也许我问错了问题?我真的不确定

如果有人可以通过解释或一些文档为我指明正确的方向,我将不胜感激:-)

【问题讨论】:

    标签: json reactjs


    【解决方案1】:

    你可以这样做:

    const ShowsTable = (props) => {
        return (
            <div>
              <h1>Show - {props.show}</h1>
              <table>
                  <tr>
                      <th>Name</th>
                      <th>Gender</th>
                  </tr>
    
                  {props.characters.map((char, index) => (
                      <tr key={index}>
                          <td>{char.name}</td>
                          <td>{char.gender}</td>
                      </tr>
                   ))}    
                </table>
            </div>
        );
    };
    

    【讨论】:

    • 像梦一样工作,我明白了我所缺少的逻辑 - 谢谢 Morreski!
    猜你喜欢
    • 2019-05-22
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多