React组件返回时无法访问属性

时间:2019-03-24 10:22:20

标签: reactjs jsx

我有一个React组件来获取商品信息并返回JSX:

const detail = props => {

    const service = new Services()

    const detail = service.findItem(props.match.params.id)
        .then(item => {
            console.log(item) // logs correct details, including the title property
            return item
        })
        .catch(err => console.log(err))

    return (
        <h1>{detail.title}</h1> // !! prints nothing inside the <h1> tag
    )
}

如上所示,返回对象正确记录了所有属性,但是当尝试通过JSX访问它们时,未显示任何信息。

没有控制台错误。

1 个答案:

答案 0 :(得分:0)

由于细节尚未解决,您可以使用React.Component并使用

export class detail extends React.Component {

  state = { 
    item: {}
  }

  componentDidMount(){
    const service = new Services()
    const detail = service.findItem(props.match.params.id)
      .then(item => {
        this.setState({ item:item });
      })
      .catch(err => console.log(err))
}

  render() {
    return <h1>{this.state.item.title}</h1>
  }

}