【问题标题】:TypeError: Cannot read property 'substr' of null - ReactTypeError:无法读取 null 的属性“substr” - React
【发布时间】:2018-05-18 17:21:52
【问题描述】:

我在 React 中有这样的代码...

import React, { Component } from 'react';

class Card extends Component {
constructor(props) {
    super(props);
    this.state = {
        eventName: props.eventName,
        eventDate: props.eventDate,
        eventDesc: props.eventDesc,
        eventPic: props.eventPic
    }
}

render () {

    const { eventDate, eventDesc, eventName, eventPic } = this.state;
    return (
        <article className="br2 ba dark-gray b--black-10 dib ma3 mw5 shadow-hover">
            <img src={eventPic} className="db w-100 br2 br--top" alt={eventName} />
            <div className="pa2 ph3-ns pb3-ns">
                <div className="dt w-100 mt1">
                    <div className="dtc">
                        <h1 className="f5 f4-ns mv0">{eventName}</h1>
                    </div>
                    <div className="dtc tr">
                        <h2 className="f5 mv0">{eventDate}</h2>
                    </div>
                </div>
                <p className="f6 lh-copy measure mt2 mid-gray">
                    {eventDesc.substr(0, 140)}
                </p>
            </div>
        </article>
    )
}
}

export default Card;

我的问题出在这个块代码中

{eventDesc.substr(0, 140)} // This is meant to limit the eventDescription's chars.

它给了我一个 TypeError: Cannot read property 'substr' of null.

您能帮我解决这个错误吗?谢谢

【问题讨论】:

  • 展示你如何渲染这个组件
  • 也许你在 eventDesc 中什么都没有。检查你有什么事件Desc
  • 您显然为 eventDesc 道具传递了一个空值。要么修复它,这样你就不会传入空值;或者,如果您想支持空值,则需要在尝试执行 null.substr(0, 140) 之前修改 Card 以检查空值

标签: javascript reactjs jsx


【解决方案1】:

基本上,您正在为eventDesc 分配一个默认值props.eventDesc 的值。但是如果你没有传递那个值(应该是undefined)或者你传递了一个null 值,你就会得到那个行为。

你可以在你的渲染中添加一个默认值来解决这个问题:

const { eventDate ="", eventDesc = "", eventName = "", eventPic = "" } = this.state;

但最好的办法是在构造函数上设置一个默认值,这样你就只做一次:

constructor(props) {
    super(props);
    this.state = {
        eventName: props.eventName || "",
        eventDate: props.eventDate || "",
        eventDesc: props.eventDesc || "",
        eventPic: props.eventPic || ""
    }
}

【讨论】:

  • 谢谢@princeHernandez,您的解决方案有效。我仍然试图理解整个概念。 ;-)
  • @RicardoSawir 如果有效,请将其标记为答案,问题还在于访问空变量,因此您应该检查父组件,它可能正在发送空道具。
猜你喜欢
  • 2020-11-25
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
相关资源
最近更新 更多