004|React之State

在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。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容