react props與stat

1. props

默認 Props

你可以通過組件類的 defaultProps 屬性爲 props 設置默認值,實例如下:

React 實例

class HelloMessage extends React.Component {

  render() {

    return (

      <h1>Hello, {this.props.name}</h1>

    );

  }

}

HelloMessage.defaultProps = {

  name: 'Runoob'

};

const element = <HelloMessage/>;

ReactDOM.render(

  element,

  document.getElementById('example')

);

 

2. State與生命週期

應用程序的 UI 是動態的,並會伴隨着時間的推移而變化。state 和 props 主要的區別在於 props 是不可變的,而 state 可以根據與用戶交互來改變。

React 把組件看成是一個狀態機(State Machines)。通過與用戶的交互,實現不同狀態,然後渲染 UI,讓用戶界面和數據保持一致。React 裏,只需更新組件的 state,然後根據新的 state 重新渲染用戶界面(不要操作 DOM)。

(1)向class組件中添加局部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>

    );

  }

}


ReactDOM.render(

  <Clock />,

  document.getElementById('root')

);

(2)掛載與卸載(構造與析構),將生命週期方法添加到 Class 中

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.getElementById('root')

);

(3)正確使用state

(a)不要直接修改state

        此代碼不會重新渲染組件:this.state.comment = 'Hello'; 應該使用setState():this.setState({comment: 'Hello'}); 構造函數是唯一可以給this.state賦值的地方。

(2)state的更新可能是異步的

        因爲 this.props 和 this.state 可能會異步更新,所以不要依賴他們的值來更新下一個狀態。例如,此代碼可能會無法更新計數器:

this.setState({

  counter: this.state.counter + this.props.increment,

});

        可以讓 setState() 接收一個函數而不是一個對象。這個函數用上一個 state 作爲第一個參數,將此次更新被應用時的 props 做爲第二個參數:

this.setState((state, props) => ({

  counter: state.counter + props.increment

}));

        上面使用了箭頭函數,不過使用普通的函數也同樣可以:

this.setState(function(state, props) {

  return {

    counter: state.counter + props.increment

  };

});

(3)state的更新會被合併

        當你調用 setState() 的時候,React 會把你提供的對象合併到當前的 state。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章