[英]Map() not returning JSX when called through a function
我正在尝试 output 一堆 li,同时遍历 map function。 问题是代码直接放在渲染返回语句中时有效,但如果我将其组织在帮助程序 function 中并在返回语句中调用 function 时,该代码将停止工作。
作品:
const UserList = (props) => {
if(props.items.length === 0){
return (
<div className="center">
<h2>No users found.</h2>
</div>
);
}
}
return <ul className="users-list">
{
props.items.map(user => {
console.log(user.name);
return <li>{user.id}</li>
})
}
</ul>
不工作:
const UserList = (props) => {
if(props.items.length === 0){
return (
<div className="center">
<h2>No users found.</h2>
</div>
);
}
}
const renderList = () => {
props.items.map(user => {
console.log(user.name);
return <li>{user.id}</li>
})
};
return <ul className="users-list">
{renderList()}
</ul>
您需要在您的方法上有 return 声明。
const { items } = props;
const renderList = () => {
return items.map(user => {
return <li>{user.id}</li>
}
)
};
或者代码更少的简短版本。 在箭头函数中,如果只返回结果而不进行进一步处理,则不需要写下花括号和return
语句。
const { items } = props;
const renderList = () => items.map(user => <li>{user.id}</li>);
做这个:
const renderList = () => {
return props.items.map(user => {
console.log(user.name);
return <li>{user.id}</li>
}
)
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.