reg*_*cob 0 javascript json reactjs
我有以下反应类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
Run Code Online (Sandbox Code Playgroud)
遗憾的是,发生了一个错误,说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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
是不是可以将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.
Run Code Online (Sandbox Code Playgroud)
您的peoples对象中有另一个peoples属性.
所以不要peoples.map(...)使用peoples.peoples.map(...)
此外,您name在map循环中错误地渲染每个:
{peoples.peoples.map(people => (
<option key={people.name}>
{people.name}
</option>
))}
Run Code Online (Sandbox Code Playgroud)
option key={people.name}
我会使用某种id或唯一的标识符代替.