繁体   English   中英

TypeError:无法读取反应中未定义的属性“子字符串”

[英]TypeError: Cannot read property 'substring' of undefined in react

我正在尝试缩短从 API 调用中获得的反应组件中的字符串,但我得到 TypeError: Cannot read property 'substring' of undefined。

这是片段:

shorten(){
    let res = this.props.details.substring(100, 0);
    return res;
}

我在渲染返回 function 中使用 function 作为:

    render(){
        return (
            <div>
                <p className="text-muted font1-1">{this.shorten()}</p>
            </div>
        );
    }

错误代码:

TypeError: Cannot read property 'substring' of undefined

摆脱缩短方法并尝试这个

render(){
    const shorten = this.props.details ? this.props.details.substring(0, 100) : '';
        return (
            <div>
                <p className="text-muted font1-1">{shorten}</p>
            </div>
        );
    }

您是否尝试过 console.log 缩短的值? 你在控制台中也没有定义吗?

如果是这样,您是否可能不等待 API 值。

你熟悉promise的概念吗? 我的假设是你得到未定义,因为你试图在没有 async/await 的情况下查看结果(或其他方式等待 promise 得到解决),这意味着你正在尝试读取它之前的值确实存在,这就是为什么你得到未定义的

在使用substring之前添加一个 null 检查,如下所示: let res = this.props.details && this.props.details.substring(100,0);

如果您确定该道具已通过,则可能有一些父级的 state 导致this.props.details未定义。

有3个解决方案。

  1. 当您通过道具时,您可以添加支票
<YourComponent details={this.state.whatever || '' } />
  1. 您可以在组件内检查它
let res = this.props.details && this.props.details.substring(100, 0);
  1. 在传递所有必需的道具并定义它们之前,不要渲染组件。

由于错误发生在 API 调用之前,请使用可选链接 ( ?. ) 检查要截断的字符串是否可用。

let res = this.props.details?.substring(100, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM