【问题标题】:How do componentDidMount and componentWillUnmount works?componentDidMount 和 componentWillUnmount 是如何工作的?
【发布时间】:2020-06-25 10:48:58
【问题描述】:

我在这里有一个简单的状态示例,称为计数器。在 componentDidMount 中,我在 console.log 期间得到 0 而不是 3,在卸载期间,我从按钮单击而不是 0 中得到计数器编号。我对它是如何工作的感到困惑?代码如下:

import React, { Component } from 'react'

class TestNumber extends Component {
    constructor(props) {
        super(props)
        this.state = {counter: 0}
    }

    componentDidMount() {
        console.log('Mount Called')
        this.setState({counter:3})
        console.log(this.state.counter)
      }
      
    componentWillUnmount() {
        this.setState({counter:0})
        console.log('Unmount Called')       
        console.log(this.state.counter)
      }

    handleClick = () => {
        this.setState({counter: this.state.counter + 1})
    }
    render() {
        return (
            <div>
                <h2>{this.state.counter}</h2>
                <button onClick={this.handleClick}>
                    Click me
                </button>
            </div>
        )
    }
}

export default TestNumber 

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    除了提出的答案。

    这里的问题不在于生命周期方法,而在于state。 在反应状态有时可以是异步的。

    反应文档:https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

    支持文章:https://medium.com/@wereHamster/beware-react-setstate-is-asynchronous-ce87ef1a9cf3

    一般来说,我们应该假设 react state 是异步的,不应该立即依赖它。 以下代码将打印正确的console.log

    this.setState({count: 3}, () => {
        console.log(this.state.counter)
    });
    

    底线

    React 状态可以是异步的

    【讨论】:

      【解决方案2】:

      这不是关于这两个生命周期方法如何工作,而是关于 setState 在 React 中是异步的,这意味着在你调用 setState 之后不会立即修改状态值,这就是为什么您可以从 console.log 中获取旧值。

      Why is setState in reactjs Async instead of Sync?

      以下示例将为您提供正确的结果。

          componentDidMount() {
              this.setState({counter:3}, () => {
                  console.log(this.state.counter);
              });
              
              console.log(this.state.counter)
          }
            
          componentWillUnmount() {
              this.setState({counter:0}, () => {
                  console.log(this.state.counter);
              });
      
              console.log('Unmount Called');      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-09
        • 1970-01-01
        • 2020-07-11
        • 2021-09-02
        相关资源
        最近更新 更多