【问题标题】:React js object properties undefined in render method在渲染方法中未定义 React js 对象属性
【发布时间】:2018-10-04 21:02:45
【问题描述】:

我正在尝试使用与 slug 属性匹配的 url 参数,使用 lodashFirebase db 中检索作为对象数组的记录。当我尝试在渲染方法中显示对象属性(例如url 属性)时,我得到TypeError: Cannot read property 'url' of undefined。如果我控制台日志this.props.match.params.slug 我得到正确的参数。

这是我从 Firebase 获得的对象:

   {
       "category" : "illustrations",
       "medium" : "ink",
       "slug" : "black-and-white",
       "thumb" : "https://.....png",
       "title" : "black and white",
       "url" : "https://.....png"
    }

这是我的组件:

import React from 'react';
import _ from 'lodash';
import base from '../base';

class Painting extends React.Component {
  constructor() {
    super()
    this.state = {
      pictures: []
    }
  }

  // firebase syncing
  componentWillMount() {
    this.ref = base.syncState('pictures', {
      context: this,
      state: 'pictures',
      asArray: true
    });
  }

  renderImage() {
    if (!this.state.pictures) {
      return ("Loading...");
    } else {
      return <p>{_.find(this.state.pictures, { slug: this.props.match.params.slug }).url}</p>
    }
  }


  render() {

    console.log(this.props.match.params.slug)

    return(
      <div>
        {this.renderImage()}
      </div>
    )
  }
}

export default Painting;

我做错了什么?

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database lodash


    【解决方案1】:

    因为你的pictures 是空的,而lodash 发现未定义。 修复你的renderImage 方法:

        renderImage() {
        if (!this.state.pictures || this.state.pictures.length === 0) {
          return ("Loading...");
        } else {
          return <p>{_.find(this.state.pictures, { slug: this.props.match.params.slug }).url}</p>
        }
     }
    

    那么,在获取图片中是否有某些项目之后,该方法将正确渲染。

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 2018-12-06
      • 2017-01-19
      相关资源
      最近更新 更多