Javascript - 从 JSON 到对象的数组

标签 javascript json reactjs

我有以下 react 类PeopleSelector,我想从我的people.json中获取一组人。

// @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.peoples.map会导致以下 react 错误:

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(...)

此外,您在 map 循环中错误地渲染了每个 name:

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

选项键={people.name}

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

关于Javascript - 从 JSON 到对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47295338/

相关文章:

javascript - 创建基于文本文件的选项菜单?

javascript - 如何在 Mobx 中执行可观察函数?

javascript - 使用 Angularjs 将动态数据从 Json 获取到 Html

reactjs - 如何屏蔽我的 Material-UI 文本字段?

javascript - ReactJS 更新数组

javascript - 如何让 jPanelMenu 不强制一切都正确?

javascript - Socket.io 客户端 : respond to all events with one handler?

javascript - 参数 'fn' 不是函数,得到字符串

java - Jersey ClientResponse 获取复合实体列表

node.js - Node-machine-id 包不工作