TypeError:this.state.user.map不是react中的函数

时间:2018-04-24 21:00:38

标签: json reactjs

我正在尝试从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

1 个答案:

答案 0 :(得分:0)

data.body是一个对象,如果您想循环优惠,则需要执行

processData (data) {
    this.setState({
        user: data.body.offers
    })
}