簡體   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