我正在尝试从rest API返回的对象中的数组中获取days_free
的值。但是,我收到错误:Uncaught TypeError: this.state.user.map is not a function
数据的结构如下:
{
"available": true,
"offers": [
{
"days_free": 30,
"description": "Woo!"
}
]
}
我正在尝试在对象中映射数组并使用
获取值const daysFree = this.state.user.map((daysFree, i) => {
return (
<span>{daysFree.days_free}</span>
)
})
来自我的组件:
class CancelOffer extends React.Component {
constructor (props) {
super(props)
this.state = {
user: []
}
this.processData = this.processData.bind(this)
}
componentDidMount () {
this.fetchContent(this.processData)
}
fetchContent (cb) {
superagent
.get('/api/data')
.then(cb)
}
processData (data) {
this.setState({
user: data.body
})
}
render () {
const content = this.props.config.contentStrings
const daysFree = this.state.user.map((daysFree, i) => {
return (
<span>{daysFree.days_free}</span>
)
})
return (
<div className='offer'>
<h2 className='offer-heading md'>Heading</h2>
<p className='offer-subpara'>text {daysFree} </p>
<div className='footer-links'>
<a href='/member' className='btn btn--primary btn--lg'>accept</a>
<a href='/' className='cancel-link'>cancel</a>
</div>
</div>
)
}
}
export default CancelOffer
答案 0 :(得分:0)
data.body
是一个对象,如果您想循环优惠,则需要执行
processData (data) {
this.setState({
user: data.body.offers
})
}