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

Why are arrow functions in reactjs sometimes treated as components?

我目前正在学习 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)的 class?

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中是一样的,第二个叫"function components"。 React doc

ReactJS 中的箭头函数被视为 功能组件 或只是 箭头函数 取决于它们 return.

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

以上组件称为无状态组件。它除了渲染道具外什么都不做。没有状态、挂钩等。

但是 react hooks 可以使有状态的组件成为可能。也就是说,功能组件可以完成 class 组件所做的一切。它可以 渲染状态 执行操作而不仅仅是 return JSX(像无状态组件)

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


要使 CommentList 成为 class 组件,可以执行以下操作:

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; 普通箭头函数和功能组件之间的区别是 return 类型,即功能组件 returns JSX.