gpt4 book ai didi

javascript - 为什么 reactjs 中的箭头函数有时被视为组件?

转载 作者:行者123 更新时间:2023-12-04 10:07:34 24 4
gpt4 key购买 nike

我目前正在学习 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 是一个组件,它怎么能写成一个带有构造函数(props)的类?

最佳答案

ReactJS 中的箭头函数被视为 功能组件或者只是一个箭头函数,具体取决于它们返回的内容。

const CommentList = comments =>
<ul>
{
comments.comments.map(
(c, index) => (
<li key = {index}>{c.body}—{c.author}</li>
)
)
}
</ul>


上述组件称为 无状态组件 .它除了渲染 Prop 什么都不做。没有状态,钩子(Hook)等。

但是可以有状态的组件可以通过 来实现。 react 钩子(Hook) .也就是说,功能组件可以做类组件所做的一切。可以 渲染状态 执行操作而不仅仅是返回 JSX(就像一个无状态组件)

要详细了解这一点,请查看 React Function Component

要使 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。

关于javascript - 为什么 reactjs 中的箭头函数有时被视为组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61495242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com