我想在我的people.json中获取一个人数组,下面有一个React类PeopleSelector

// @flow

import React from 'react'

type Props = {
  currentPeople: string,
  setPeopleFn: (string) => void
}

class PeopleSelector extends React.Component {
  render() {
    let peoples = require('../data/people.json');

    return <select value={this.props.currentPeople} onChange={e => this.props.setPeopleFn(e.target.value)}>
      <style jsx>{`
        select {
          font-size: 20px;
          line-height: 20px;
          margin-bottom: 20px;
          min-width: 300px;
        }
      `}</style>
      {peoples.map(name => (
        <option key={name}>
          {name}
        </option>
      ))}
    </select>
  }
}

export default PeopleSelector


不幸的是,发生错误,指出people.map不是一个函数。但为什么?

我的JSON看起来像

{
    "peoples": [
        {
            "focusedTrackId": "MOBILE",
            "milestoneByTrack": {
                "COMMUNICATION": 3,
                "CRAFT": 2,
                "DESKTOP": 0,
                "MENTORSHIP": 2,
                "MOBILE": 3,
                "PROJECT_MANAGEMENT": 3,
                "SERVER": 0
            },
            "name": "Bocksteger, Daniel",
            "title": "Entwickler I"
        }
    ]
}


不可能将JSON渲染为人的对象吗?

使用peoples.peoples.map会导致以下反应错误:

Objects are not valid as a React child (found: object with keys
{focusedTrackId, milestoneByTrack, name, title}). If you meant to
render a collection of children, use an array instead.

最佳答案

您的peoples对象具有另一个peoples属性。

因此,使用peoples.map(...)代替peoples.peoples.map(...)

另外,您在name循环内错误地渲染了每个map

{peoples.peoples.map(people => (
  <option key={people.name}>
    {people.name}
  </option>
))}


option key={people.name}

我会使用某种id或唯一标识符代替。

10-07 17:29