我有以下反应类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.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.
答案 0 :(得分:5)
您的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
或唯一标识符。
答案 1 :(得分:0)
我认为你打算做peoples.peoples.map(name =&gt; {});
当您需要json文件时,您将其作为根对象导入。那么人民阵列将(导入为)。人民。即peoples.peoples.map();
答案 2 :(得分:0)
您可以干净地提取(破坏)您真正需要的部分,如下所示:
let { peoples } = require('../data/people.json');