生命周期图解image.png

函数定义组件

  1. function Clock(props) {
  2. return (
  3. <div>
  4. <h1>Hello, world!</h1>
  5. <h2>It is {props.date.toLocaleTimeString()}.</h2>
  6. </div>
  7. );
  8. }
  9. function tick() {
  10. ReactDOM.render(
  11. <Clock date={new Date()} />,
  12. document.getElementById('root')
  13. );
  14. }
  15. setInterval(tick, 1000

然而,它错过了一个关键的要求:Clock设置一个定时器并且每秒更新UI应该是Clock的实现细节。
理想情况下,我们写一次 Clock 然后它能更新自身:

  1. ReactDOM.render(
  2. <Clock />,
  3. document.getElementById('root')
  4. );

为了实现这个需求,我们需要为Clock组件添加”状态(state)”
状态与属性十分相似,但是状态是私有的,完全受控于当前组件。
我们之前提到过,定义为类的组件有一些额外的特性。局部状态就是如此:只能用于类的一个功能。

将函数转换为类(特有局部状态)

你可以通过5个步骤将函数组件 Clock 转换为类

  1. 创建一个名称扩展为 React.Component 的ES6 类
  2. 创建一个叫做render()的空方法
  3. 将函数体移动到 render() 方法中
  4. 在 render() 方法中,使用 this.props 替换 props
  5. 删除剩余的空函数声明
    1. class Clock extends React.Component {
    2. render() {
    3. return (
    4. <div>
    5. <h1>Hello, world!</h1>
    6. <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
    7. </div>
    8. );
    9. }
    10. }

Clock 现在被定义为一个类而不只是一个函数
使用类就允许我们使用其它特性,例如局部状态、生命周期钩子

为一个类添加局部状态

我们会通过3个步骤将 date 从属性移动到状态中:

  1. 在 render() 方法中使用 this.state.date 替代 this.props.date

    1. class Clock extends React.Component {
    2. render() {
    3. return (
    4. <div>
    5. <h1>Hello, world!</h1>
    6. <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    7. </div>
    8. );
    9. }
    10. }
  2. 添加一个类构造函数来初始化状态 this.state

    1. class Clock extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = {date: new Date()};
    5. }
    6. render() {
    7. return (
    8. <div>
    9. <h1>Hello, world!</h1>
    10. <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    11. </div>
    12. );
    13. }
    14. }

    注意我们如何传递 props 到基础构造函数的:

    1. constructor(props) {
    2. super(props);
    3. this.state = {date: new Date()};
    4. }

    类组件应始终使用props调用基础构造函数。

  3. 从 <Clock /> 元素移除 date 属性:

    1. ReactDOM.render(
    2. <Clock />,
    3. document.getElementById('root')
    4. );

    稍后将定时器代码添加回组件本身。
    结果如下:

    1. class Clock extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = {date: new Date()};
    5. }
    6. render() {
    7. return (
    8. <div>
    9. <h1>Hello, world!</h1>
    10. <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    11. </div>
    12. );
    13. }
    14. }
    15. ReactDOM.render(
    16. <Clock />,
    17. document.getElementById('root')
    18. );

    接下来,我们将使Clock设置自己的计时器并每秒更新一次。

    将生命周期方法添加到类中

    在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。
    每当Clock组件第一次加载到DOM中的时候,我们都想生成定时器,这在React中被称为挂载
    同样,每当Clock生成的这个DOM被移除的时候,我们也会想要清除定时器,这在React中被称为卸载。
    我们可以在组件类上声明特殊的方法,当组件挂载或卸载时,来运行一些代码:

    1. class Clock extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = {date: new Date()};
    5. }
    6. componentDidMount() {
    7. }
    8. componentWillUnmount() {
    9. }
    10. render() {
    11. return (
    12. <div>
    13. <h1>Hello, world!</h1>
    14. <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    15. </div>
    16. );
    17. }
    18. }

    这些方法被称作生命周期钩子。
    当组件输出到 DOM 后会执行 componentDidMount() 钩子,这是一个建立定时器的好地方:

    1. componentDidMount() {
    2. this.timerID = setInterval(
    3. () => this.tick(),
    4. 1000
    5. );
    6. }

    注意我们是将定时器ID保存在 this 中的。
    尽管 this.props 是由React本身安装的以及this.state 有特殊的含义,如果你需要存储的东西不在数据流中,你可以随意手动向类中添加其他字段(比如定时器ID)。
    我们将在 componentWillUnmount()生命周期钩子中卸载计时器:

    1. componentWillUnmount() {
    2. clearInterval(this.timerID);
    3. }

    最后,我们实现了每秒钟执行的 tick() 方法。
    它将使用 this.setState() 来更新组件局部状态:

    1. class Clock extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = {date: new Date()};
    5. }
    6. componentDidMount() {
    7. this.timerID = setInterval(
    8. () => this.tick(),
    9. 1000
    10. );
    11. }
    12. componentWillUnmount() {
    13. clearInterval(this.timerID);
    14. }
    15. tick() {
    16. this.setState({
    17. date: new Date()
    18. });
    19. }
    20. render() {
    21. return (
    22. <div>
    23. <h1>Hello, world!</h1>
    24. <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
    25. </div>
    26. );
    27. }
    28. }
    29. ReactDOM.render(
    30. <Clock />,
    31. document.getElementById('root')
    32. );

    在 CodePen 中尝试
    现在时钟每秒钟都会执行。
    让我们快速回顾一下发生了什么以及调用方法的顺序:

  4. 当 <Clock /> 被传递给 ReactDOM.render() 时,React 调用 Clock 组件的构造函数。 由于 Clock 需要显示当前时间,所以使用包含当前时间的对象来初始化 this.state 。 我们稍后会更新此状态。

  5. React 然后调用 Clock 组件的 render() 方法。这是 React 了解屏幕上应该显示什么内容,然后 React 更新 DOM 以匹配 Clock 的渲染输出。
  6. 当 Clock 的输出插入到 DOM 中时,React 调用 componentDidMount() 生命周期钩子。 在其中,Clock 组件要求浏览器设置一个定时器,每秒钟调用一次 tick()。
  7. 浏览器每秒钟调用 tick() 方法。 在其中,Clock 组件通过使用包含当前时间的对象调用 setState() 来调度UI更新。 通过调用 setState() ,React 知道状态已经改变,并再次调用 render() 方法来确定屏幕上应当显示什么。 这一次,render() 方法中的 this.state.date 将不同,所以渲染输出将包含更新的时间,并相应地更新DOM。
  8. 一旦Clock组件被从DOM中移除,React会调用componentWillUnmount()这个钩子函数,定时器也就会被清除。

    正确地使用状态

    关于 setState() 这里有三件事情需要知道

    不要直接更新状态

    例如,此代码不会重新渲染组件:
    1. // Wrong
    2. this.state.comment = 'Hello';
    应当使用 setState():
    1. // Correct
    2. this.setState({comment: 'Hello'});
    构造函数是唯一能够初始化 this.state 的地方。

    状态更新可能是异步的

    React 可以将多个setState() 调用合并成一个调用来提高性能。
    因为 this.props 和 this.state 可能是异步更新的,你不应该依靠它们的值来计算下一个状态。
    例如,此代码可能无法更新计数器:
    1. // Wrong
    2. this.setState({
    3. counter: this.state.counter + this.props.increment,
    4. });
    要修复它,请使用第二种形式的 setState() 来接受一个函数而不是一个对象。 该函数将接收先前的状态作为第一个参数,将此次更新被应用时的props做为第二个参数:
    1. // Correct
    2. this.setState((prevState, props) => ({
    3. counter: prevState.counter + props.increment
    4. }));
    上方代码使用了箭头函数,但它也适用于常规函数:
    1. // Correct
    2. this.setState(function(prevState, props) {
    3. return {
    4. counter: prevState.counter + props.increment
    5. };
    6. });

    状态更新合并

    当你调用 setState() 时,React 将你提供的对象合并到当前状态。
    例如,你的状态可能包含一些独立的变量:
    1. constructor(props) {
    2. super(props);
    3. this.state = {
    4. posts: [],
    5. comments: []
    6. };
    7. }
    你可以调用 setState() 独立地更新它们:
    1. componentDidMount() {
    2. fetchPosts().then(response => {
    3. this.setState({
    4. posts: response.posts
    5. });
    6. });
    7. fetchComments().then(response => {
    8. this.setState({
    9. comments: response.comments
    10. });
    11. });
    12. }
    这里的合并是浅合并,也就是说this.setState({comments})完整保留了this.state.posts,但完全替换了this.state.comments。