代码之家  ›  专栏  ›  技术社区  ›  Robin

在构造函数ReactJS中设置状态

  •  1
  • Robin  · 技术社区  · 6 年前

    我在ReactJS教程中看到了处理状态的不同变体。

    我看到了以下情况:

    class App extends Component {
        constructor () {
            super()
            this.state = {
                message: null,
            };
        }    
    
        componentDidMount() {
            fetch('/api/hello')
               .then(response => response.json())
               .then(message => this.setState({ message }));
        }
    }
    

    class App extends Component {
        state = {};
    
        hello = () => {
            fetch("/api/hello")
               .then(response => response.text())
               .then(message => this.setState({ message }));
        };
    }
    

    两者的行为都符合预期,即它能够从 /api/hello . 我想知道两者之间的区别,一个在构造函数中设置状态,另一个不设置状态。

    1 回复  |  直到 6 年前
        1
  •  0
  •   rileyjsumner    6 年前

    state 本质上是一个类字段,因此在该字段中设置它需要 this. 前缀,而将其视为类字段,而不在构造函数中设置则不需要 这个。 . 关键的区别在于,当放入构造函数时,状态是在类被实例化时设置的,而当它在构造函数之外时,它属于该类。