首页 > 解决方案 > 可以根据 id 找到一个对象,然后在反应组件中渲染它

问题描述

我想根据它找到一个对象,id然后在组件中渲染它。

getInitialState() {
  return { item: [] }
 },

componentDidMount() {
  this.setState({item: this.props.items.filter(item => (item.id == this.props.match.params.id))})
}
componentDidUpdate() {
  console.log(this.state.item) // result is empty array
}

如果我不想setState在方法中使用和查找对象,render那么我将得到:

render() {
  var item = this.props.items.find(item => (item.id == this.props.match.params.id))
  console.log(item) // First it is undefined then it will be found
  var title = item.title
  return (
    <div>
      {title}
    </div>

如何根据params.id然后在组件内渲染它来找到对象?

标签: reactjs

解决方案


render() {
  var item = this.props.items.find(item => (item.id == this.props.match.params.id))


  //This is what you should do to show that it's loading.
  if(!item || !item.id){
    return <div>Loading</div>
  }


  console.log(item) // First it is undefined then it will be found
  var title = item.title
  return (
    <div>
      {title}
    </div>

推荐阅读