2018-11-06 生命周期

1???1? ???
?? ??? ?? ??? ??

以前使用render來更新UI

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>
        {new Date().toLocaleTimeString()}.
      </h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.querySelector('#root')
  );
}

setInterval(tick, 1000);

可以看到我們把整個(gè)的函數(shù)都更新了

我們可以改進(jìn)下這個(gè)方案,單獨(dú)把時(shí)鐘Clock封裝起來,就是我們?nèi)绾螌懸淮蜟lock組件就能讓時(shí)鐘自動(dòng)開始更新

class Clock extends React.Component {
constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>
          {this.state.date.toLocaleTimeString()}.
        </h2>
      </div>
    );
  }
}
ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

將生命周期方法添加到類中
每當(dāng)Clock組件第一次加載到DOM中的時(shí)候,我們都想生成定時(shí)器,這在React中被稱為掛載
同樣,每當(dāng)Clock生成的這個(gè)DOM被移除的時(shí)候,我們也會(huì)想要清除定時(shí)器,這在React中被稱為卸載。

在掛載時(shí)候建立定時(shí)器:

 componentDidMount() {
    var this.timer = setInterval(()=>{
      this.tick();
},1000)
  }

在卸載的時(shí)候清除定時(shí)器:

 componentWillUnmount() {
    clearInterval(this.timer);
  }

tick是一個(gè)改變狀態(tài)的函數(shù);

tick=()=>{
  this.setState(){
  date:new.Date()
}
}

完整的代碼:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.querySelector('#root')
);

數(shù)據(jù)流向問題:
數(shù)據(jù)自頂向下流動(dòng):組件可以選擇將其狀態(tài)作為屬性傳遞給其子組件,稱為自頂向下或單向數(shù)據(jù)流
父組件

<App name={this.state.name}/>

子組件

console.log(this.props.name)

如果父組件需要使用子組件中的數(shù)據(jù):
父組件

var fn = (ele)=>{
console.log(ele);
}

<App fn={this.fn}/>

子組件

var fe = ()=>{
  this.props.fn(ele);
}

這樣父組件就可以拿到子組件傳來的數(shù)據(jù)了?。。?/p>

關(guān)于setState的問題,

  • setstate是異步的
  • 第一個(gè)參數(shù)可以是
    1.object
    2.function(上一次的狀態(tài))
  • 關(guān)于setState的兩個(gè)參數(shù),第二個(gè)參數(shù)是一個(gè)callback,是可選的,只有在第二個(gè)參數(shù)里才能取得最新的和UI同步的狀態(tài)。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

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

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