簡體   English   中英

TypeError:無法在 React 中讀取 null 的屬性“url”

[英]TypeError: Cannot read property 'url' of null in React

使用Reactstyled組件。

我正在嘗試對徽標進行條件渲染。 在我的反應組件<Header>應該只在沒有徽標時呈現。 這里的標志被檢查為來自companies數組的companies[currentCompanyIndex].logo.url

 <HeaderContainer>
        <Header>
          {!companies[currentCompanyIndex].logo.url &&
            companies[currentCompanyIndex].name}
        </Header>

        {companies[currentCompanyIndex].logo.url && (
          <Logo
            src={companies[currentCompanyIndex].logo.url}
            alt={`${companies[currentCompanyIndex].logo.url}-img`}
          />
        )}
 </HeaderContainer>

問題TypeError: Cannot read property 'url' of null 在許多情況下,只有name呈現為 header 而沒有徽標。 因此,在許多情況下,數據將為 null。 雖然我已經提出了條件,但我仍然得到錯誤。 如何處理這個問題?

僅在沒有徽標時才預期呈現 header。 有 logo 時,忽略 header,只渲染 logo。

您沒有檢查companies[currentCompanyIndex].logo存在,這就是您收到此錯誤的原因。

您應該在 Header 組件內部和外部(渲染徽標的位置)都進行檢查

您所做的只會檢查 logo.url 是否未定義。 它不會檢查它是否是 null。 編輯您的代碼,如下所示:

<HeaderContainer> <Header> {!companies[currentCompanyIndex].logo.url &&  companies[currentCompanyIndex].name} </Header> {companies[currentCompanyIndex].logo.url && companies[currentCompanyIndex].logo.url !== null && ( <Logo src={companies[currentCompanyIndex].logo.url} alt={`${companies[currentCompanyIndex].logo.url}-img`} /> )} </HeaderContainer>

我希望這能解決你的問題。 除了未定義之外,您還需要檢查它是否不是 null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM