0
点赞
收藏
分享

微信扫一扫

React Hook使用之useEffect

九点韶留学 2022-02-24 阅读 141

组件的写法

传统的class组件的写法

这是一个 React 计数器的 class 组件。它在 React 对 DOM 进行操作之后,立即更新了 document 的 title 属性。


class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }
  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

由于需要修改document的title属性,不能直接进行绑定,所以需要在组件更新的时候使用代码同步更新title属性的值。同时更新需要在react的生命周期中执行操作,包括了componentDidMountcomp

举报

相关推荐

0 条评论