在react函数中渲染对象数组

时间:2016-05-05 20:31:36

标签: javascript reactjs

原谅我,我是一个反应菜鸟。我正在尝试访问javascript / react对象中的数据。 json数据如下所示:

"schoolData": {
      "student": [
        {
          "name": "blah",
          "type": "lorem",
          "grade": 90,
        }
      ],
      "class": null
    },

我想要展示的内容基本上就是这样...

Student
name: Blah      type: lorem      grade:   90
Class
--- no data here ---

所以我这样想:

import React, { PropTypes } from 'react';


const SchoolDataPropTypes = {
  SchoolData: PropTypes.object.isRequired,
};

function School(props) {

    return (
    <div className="section">
        <h3 className="head">School Data</h3>
        <div className="row">

            <ul className="Uli">
                {(props.data || []).map(function(value) {
                    return <label>{props.data.key}</label><li key={value}>{key}: {value}</li>
                })}
            </ul>
        </div>
    </div>
  );
}
School.propTypes = SchoolPropTypes;

export default School;

显然不起作用。这样我就可以在对象中渲染每个数组了吗?

1 个答案:

答案 0 :(得分:1)

理想情况下,您可以手动指定每个键。

select t.* 
    from (select m.*, @g := 0
        from MyTable m --here i have a big query
        order by id, record_date) t
    where (1 = case when @g = 0 or @g <> id then 1 else  0 end )
          and (@g := id) IS NOT NULL

等...

但是如果你真的想循环遍历student对象中的变量键,那么基本上你需要遍历学生数组,然后循环遍历每个学生对象中的键。这是它的样子:

{(schoolData.student || []).map(student => (
  <ul className="Uli">
    <li>Name: {student.name}</li>
    <li>Grade: {student.grade}</li>
  </ul>
))}

-

const School = ({ schoolData }) => (
  <div className="section">
    <h3 className="head">School Data</h3>
    <div className="row">
      {(schoolData.student || []).map(student => (
        <ul className="Uli">
          {Object.keys(student).map(key => (
            <li key={key}>{key}: {student[key]}</li>
          ))}
        </ul>
      ))}
    </div>
  </div>
);

如果您定位的是非常旧的浏览器,则可能需要<School schoolData={schoolData} />

的polyfill