2017-08-21 19 views
-1

我試圖讓這個組件渲染,我不斷收到錯誤A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.我不知道是什麼問題,因爲如果沒有什麼可返回,我將返回nullReact組件錯誤undefined,但應該返回null

有什麼想法?

組件:CompanyLogo

function CompanyLogo(props) { 
    props.companies.map((company) => { 
    if (props.companyId == company._id) { 
     console.log("Test to see if firing"); 
     return <p>Return as a test</p>; 
    } 
    return null 
    }) 
} 

回答

1

Maximum Number of JSX Root Nodes

從文檔,

目前,在組件的渲染,你可以只返回一個節點;如果你有,比如說,div的列表返回,你必須一個div,跨度或任何其他組件

function CompanyLogo(props) { 
    props.companies.map((company) => { 
    if (props.companyId == company._id) { 
     console.log("Test to see if firing"); 
     return (<p>Return as a test</p>); 
    } 
    return (<p></p>) 
    }) 
} 

您可以刪除冗餘return語句內換你的組件,

function CompanyLogo(props) { 

    let component = <p></p>; 
    props.companies.map((company) => { 
     if (props.companyId == company._id) { 
      console.log("Test to see if firing"); 
      component = <p>Return as a test</p>; 
     } 
    }); 
    return component; 
} 
+0

很好的答案。奇蹟般有效。 – bp123

+0

使用'.some()',而不是'.map'。如果你的比賽是說,標誌#2,你有50多,爲什麼繼續循環? –

+0

@DimitarChristoff謝謝。 –

0

CompanyLogo(props)函數不返回任何東西。它應該返回的東西,嘗試添加return的功能:

function CompanyLogo(props) { 
    let elementsArr = props.companies.map((company) => { 
    if (props.companyId == company._id) { 
     console.log("Test to see if firing"); 
     return <p>Return as a test</p>; 
    } 

    return null; 
    }); 

    return (<div>{elementsArr}</div>); 
} 

你必須確保映射props.companies是一個有效的做出反應元素雖然。

+0

仍然收到相同的錯誤。 – bp123

+0

@ bp123我的不好,我編了代碼 – samAlvin

0

原因是你從CompanyLogo方法中沒有返回任何東西,你使用return map函數體很簡單。

寫這樣的:

function CompanyLogo(props) { 
    let result = props.companies.map((company) => { 
     if (props.companyId == company._id) { 
       return <p>Return as a test</p>; 
     } 
     return null; 
    }); 
    return <div> {result} </div>  //add this return 
} 

相同的代碼,你可以通過使用ternary operator寫這樣的:

function CompanyLogo(props) { 
    let result = props.companies.map(company => props.companyId == company._id ? 
      <p> Return as a test </p> 
     : 
      null 
    }); 
    return <div> {result} </div> //add this return 
} 

建議map是有益的,當我們想要返回的東西每個價值,這裏只有一家公司會滿足條件,所以在這種情況下,地圖不是循環所有公司的正確方法,更好使用Array.prototype.find()

相關問題