TypeError:无法读取null的属性'substr' - React

时间:2018-05-18 17:21:53

标签: javascript reactjs jsx

我在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:无法读取null的属性'substr'。

你能帮我解决一下这个错误吗?谢谢

1 个答案:

答案 0 :(得分: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 || ""
    }
}