我有以下 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/