我现在正在学习reactjs,我很难理解为什么reactjs中的箭头函数有时会被当作组件处理,有时只是当作普通的箭头函数处理。
在这个例子中。
class CommentListContainer extends React.Component {
state = { comments : [] };
componentDidMount() {
fetchSomeComments(s => // 1- here fetchSomeComments is treated as a normal arrow function
this.setState({ comments: s }));
}
render() {
return <CommentList comments={this.state.comments} />; // 2- here CommentList is treated as a component
}
}
// 1
const fetchSomeComments = cb =>
cb([
{ author: "Chan", body: "You look nice today." },
{ author: "You", body: "I know, right?!" }
]);
// 2
const CommentList = comments =>
<ul>
{
comments.comments.map(
(c, index) => (
<li key = {index}>{c.body}—{c.author}</li>
)
)
}
</ul>
我想了解一下 如果CommentList是一个组件 怎么能把它写成一个有构造函数的类?
在ReactJS中,一个箭头函数要么被认为是一个 功能部件 抑或只是 箭头功能 根据它们返回的内容。
const CommentList = comments => <ul> { comments.comments.map( (c, index) => ( <li key = {index}>{c.body}—{c.author}</li> ) ) } </ul>
上述组件被称为 无状态组件. 它除了渲染道具外,什么也不做。没有状态,钩子等。
但是,可以有状态的组件是可以通过 反应钩. 也就是说,一个功能组件可以做类组件所做的一切。它可以 渲染状态 执行操作,而不仅仅是返回JAX(像一个无状态组件)。
要想详细了解这个问题,可以看一下。React函数组件
要使CommentList成为一个类组件,可以做以下工作。
class CommentList extends React.Component {
constructor(props) {
super(props);
}
render () {
/* destructuring props so that we can use "comments" prop directly instead of
using this.props.comments */
const {comments}=this.props;
return (
<ul>
{comments.comments.map((c, index) => (
<li key={index}>
{c.body}—{c.author}
</li>
))}
</ul>
);
}
}
TLDR;普通的箭头函数和功能组件的区别在于返回类型,即功能组件返回的是JSX。
class CommentList extends React.Component {
construct(props) {
super(props);
}
render() {
let list_items = [];
for(let c of this.props.comments) {
list_items.push(<li key = {index}>{c.body}—{c.author}</li>);
}
return (
<ul>{list_items}</ul>
);
}
}
function CommentList(props) {
let list_items = [];
for(let c of props.comments) {
list_items.push(<li key = {index}>{c.body}—{c.author}</li>);
}
return (<ul>{list_items}</ul>);
}
它们在React中是一样的,第二种叫做 "函数组件"。React文档