在构造函数ReactJS中设置状态

时间:2018-10-31 15:02:39

标签: reactjs

我在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 个答案:

答案 0 :(得分:0)

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