在JSX中蜘矢,每一個組件除了props屬性外悼枢,還有一個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有一些要點要注意。首先动羽,不要直接修改state對象,而要通過setState方法渔期。直接修改state對象不會觸發(fā)重新繪制运吓。
// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});
為了性能,React有可能將多個setState合并為一個setState調(diào)用疯趟。這會導(dǎo)致state拘哨、props異步,從而以下調(diào)用出錯:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
使用setState的函數(shù)模式信峻,即可蔽免這個問題:
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
State的一級屬性可以通過setState單獨更新倦青,如:
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
this.setState({
posts: response.posts
}); // 只更新posts屬性,而comments屬性依舊會保留
}
組件加載與卸載
如果實現(xiàn)了componentDidMount方法盹舞,則當(dāng)組件被加載時产镐,此方法會被調(diào)用。
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
如果實現(xiàn)了componentWillUnmount方法踢步,則當(dāng)組件被卸載時癣亚,此方法會被調(diào)用。
componentWillUnmount() {
clearInterval(this.timerID);
}
組件中如何處理事件获印?
好述雾,這一節(jié)就到這里。后續(xù)我將逐步介紹React技術(shù)細(xì)節(jié)兼丰,來慢慢解答上述問題玻孟。
想學(xué)計算機(jī)技術(shù)嗎?需要1對1專業(yè)級導(dǎo)師指導(dǎo)嗎鳍征?想要團(tuán)隊陪你一起進(jìn)步嗎?歡迎加我為好友黍翎!微信號:iTekka。