2017-08-21 22 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()

相关问题