状态在componentDidUpdate中不可访问

我目前正在学习React Hooks。

我试图将状态值访问到我的类组件的componentDidUpdate()函数中,但是没有显示出来,我也无法弄清楚为什么。相反,可以在componentDidMount()函数中访问相同的状态值。

Can somebody please help me to understand what might be the problem and its possible solution because the same example is working fine on the youtube tutorial (link) I am referring to.

Link to CodeSandBox: link

样例代码

import React, { Component } from "react";

class ClassCounter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = "Clicked {this.state.count} times.";
  }

  componentDidUpdate(prevProps, prevState) {
    document.title = "Clicked {this.state.count} times.";
    alert("Clicked ${this.state.count} times.");
  }

  render() {
    return (
      <div>
        <p>From Class Component.</p>
        <p>You clicked {this.state.count} number of times.</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Clicked {this.state.count} times.
        </button>
      </div>
    );
  }
}

export default ClassCounter;
评论
  • 美国内衣
    美国内衣 回复

    您使用了错误的语法,请使用``

        componentDidMount() {
        document.title = `Clicked ${this.state.count} times.`;
      }
    
      componentDidUpdate(prevProps, prevState) {
        document.title = `Clicked ${this.state.count} times.`;
        alert(`Clicked ${this.state.count} times.`);
      }
    
  • 萌了个兔
    萌了个兔 回复

    Your string interpolation syntax in componentDidMount and in componentDidUpdate is wrong. The correct syntax:

    document.title = `Clicked ${this.state.count} times.`;
    

    请注意反引号(`)和$字符。