在JSX中,每一個(gè)組件除了props屬性外,還有一個(gè)state屬性。注意state全部為小寫。
例如,下面的代碼中,在constructor中初始化state,然后在render中引用state:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()}; // 初始化
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2> // 引用
</div>
);
}
}
state有一些要點(diǎn)要注意。首先,不要直接修改state對象,而要通過setState方法。直接修改state對象不會(huì)觸發(fā)重新繪制。
// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});
為了性能,React有可能將多個(gè)setState合并為一個(gè)setState調(diào)用。這會(huì)導(dǎo)致state、props異步,從而以下調(diào)用出錯(cuò):
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
使用setState的函數(shù)模式,即可蔽免這個(gè)問題:
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
State的一級屬性可以通過setState單獨(dú)更新,如:
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
this.setState({
posts: response.posts
}); // 只更新posts屬性,而comments屬性依舊會(huì)保留
}
組件加載與卸載
如果實(shí)現(xiàn)了componentDidMount方法,則當(dāng)組件被加載時(shí),此方法會(huì)被調(diào)用。
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
如果實(shí)現(xiàn)了componentWillUnmount方法,則當(dāng)組件被卸載時(shí),此方法會(huì)被調(diào)用。
componentWillUnmount() {
clearInterval(this.timerID);
}
組件中如何處理事件?
好,這一節(jié)就到這里。后續(xù)我將逐步介紹React技術(shù)細(xì)節(jié),來慢慢解答上述問題。
想學(xué)計(jì)算機(jī)技術(shù)嗎?需要1對1專業(yè)級導(dǎo)師指導(dǎo)嗎?想要團(tuán)隊(duì)陪你一起進(jìn)步嗎?歡迎加我為好友!微信號:iTekka。