我正在尝试遍历功能组件内的一个简单数组,以便它返回数组内的名称列表。我得到的错误是Person(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
const Person = () => {
var persons = ["John", "Ron"];
persons.map(p => {
return (
<div>
<ul>
<li> I am {p} </li>
</ul>
</div>
)
})
}
答案 0 :(得分:1)
您必须返回map
的结果数组,否则undefined
组件将返回Person
,这是React不允许的。
const Person = () => {
var persons = ["John", "Ron"];
return persons.map(p => (
<div key={p}>
<ul>
<li> I am {p} </li>
</ul>
</div>
));
};
ReactDOM.render(<Person />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.4.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.4.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
答案 1 :(得分:1)
<li>
,因为它是列表项。
const Person = () => {
var persons = ["John", "Ron"];
return (
<div>
<ul>
{
persons.map((p,i) => {
return (<li key={i}> I am {p} </li>)
})
}
</ul>
</div>
)
};
ReactDOM.render(<Person />, document.getElementById("root"));
<script src="https://unpkg.com/react@16.4.2/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.4.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>