React--State & 生命周期

常用生命周期

constructor()

用途: 初始化 propsstate,用來寫bind this

class Parent entends React.Component{
  constructor(props){
    super(props)
    this.state = { name: 'fanison' }
    this.onClick = this.onClick.bind(this)
  }
  // 新語法
  onClick = ()=> {}
}

shouldComponentUpdate()

用途:

  • 返回 true 表示不阻止UI更新
  • 返回 false 表示阻止UI更新
  • 允許我們手動判斷是否要進行組件更新,可以根據(jù)應用場景靈活地設置返回值,以避免不必要的更新。
  onClick = () =>{
    // 先加一,再減一; 新對象與舊對象地址不同,會render兩次
    this.setState(state => ({n: state.n +1}));
    this.setState(state =>({n: state.n - 1}));
  };
  // 使用  shouldComponentUpdate 對比 nextState和 this.state的每個屬性,如果全都相等,就不更新;如果有一個不等,就更新
  shouldComponentUpdate(nextProps,nextState){
    if(nextState.n === this.state.n){
      return false
    }else{
      return true
    }
  }
render(){
    console.log('render了一次')
    return(
      <div>
        {this.state.n}
        <button onClick={this.onClick}>+1-1</button>
      </div>
    )
  }

補充: 大多數(shù)情況可以使用 React.PureComponent代替 shouldComponentUpdate()

PureComponent 會在 render 之前對比新 state 和舊 state 的每一個 key,以及新 props 和舊 props 的每一個 key。
如果所有 key 的值全都一樣,就不會 render;如果有任何一個 key 的值不同,就會 render。

class App extends React.PureComponent{
  constructor(props) {
    super(props);
    this.state = {
      n : 1
    };
  }
  onClick = () =>{
    this.setState(state => ({n: state.n +1}));
    this.setState(state =>({n: state.n - 1}));
  };
  render(){
    console.log('render了一次')
    return(
      <div>
        {this.state.n}
        <button onClick={this.onClick}>+1-1</button>
      </div>
    )
  }
}
export default App;

render()

用途:

  • 展示視圖 return (<div>...</div>)
  • 只能有一個根元素
  • 如果有兩個根元素,要用<React.Fragment>包起來
  • <React.Fragment /> 可以縮寫成 <></>
//render 里面可以寫 if...else
render(){
    let message
    if(this.state.n % 2 === 0 ){
      message = <div>偶數(shù)</div>
    }else{
      message = <div>奇數(shù)</div>
    }
    return(
      <div>
        {message}
        <button onClick={this.onClick}>+1</button>
      </div>
    )
  }

// render 里面可以寫?:表達式
render(){
    return(
      <div>
        {this.state.n % 2 === 0 ? <div>偶數(shù)</div>:<span>奇數(shù)</span>}
        {this.state.n % 2 === 0 ? <div>偶數(shù)</div>:null}
        {this.state.n % 2 === 0 && <div>偶數(shù)</div>}
        <button onClick={this.onClick}>+1</button>
      </div>
    )
  }

// render里面不能直接寫for循環(huán),需要用數(shù)組
render(){
    let result = []
    for(let i=0;i<this.state.array.length;i++){
      result.push(this.state.array[i])
    }
    return(
      <div>
        {result}
      </div>
    )
  }

// render里面可以寫 array.map(循環(huán))
render(){
    return(
      <div>
        {this.state.array.map(n=><span key={n}>{n}</span>)}
      </div>
    )
  }

componentDidMount() 組件已出現(xiàn)在頁面

用途:

  • 在元素插入頁面后執(zhí)行代碼,這些代碼依賴DOM
  • 可以發(fā)起加載數(shù)據(jù)的 AJAX 請求
  • 首次渲染會執(zhí)行此鉤子
  • 可在此處獲取div高度
class App extends React.PureComponent{
  constructor(props) {
    super(props);
    this.state = {
      width:undefined
    };
    this.divRef = React.createRef();
  }

componentDidMount(): void {
  const div = document.getElementById('xxx')
  console.log(div)
  const width = div.getBoundingClientRect().width
  this.setState({width:width})
  // 使用 divRef.current
  const div2 = this.divRef.current
  console.log(div2)
  const {width} = div2.getBoundingClientRect()
  this.setState({width:width})
}

 render(){
   return(
     <>
      <div id="xxx"> GetElementById: {this.state.width} px </div>
      <div ref={this.divRef}>Hello,World {this.state.width} px </div>
     </>
   )
 }

componentDidUpdate() //組件已更新

componentWillUnmount() //組件將死

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

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