React state和props使用場景

一個組件的顯示狀態能夠由內部狀態state、外部參數props所決定。javascript

props:java

  一、props 是從外部傳進組件的參數,主要是父組件向子組件傳遞數據。服務器

  二、props 對於使用它的組件來講是隻讀的。要想修改props,必須經過父組件修改。因此子組件的props 一般是父組件的state。this

  三、默認值spa

    爲了組件的健壯性,在傳入props 的時候常給默認值。對象

const SubComponent=(props)=> {
  return (<h1>{props.name}</h1>)
}
SubComponent.defaultProps = {
  name: 'Rain_tdk'
};
export default SubComponent

  四、爲開發方便咱們須要對props 的數據類型進行檢驗blog

import PropTypes from 'prop-types';
const SubComponent=(props)=> {
  return (<h1>{props.name}</h1>)
}
SubComponent.defaultProps = {
  name: 'Rain_tdk'
};
SubComponent.propTypes = {
  name: PropTypes.string
};
export default SubComponent

  更多檢驗參考 :https://www.jianshu.com/p/2896acb5746b事件

state:ip

  一、state是React組件中的私有對象,用於控制這個組件自己的狀態開發

  二、setState()採用merge的方式修改state。setState會從新調用render()刷新UI,直接經過this.state=‘xxx’的方式也會修改state可是不會從新渲染。

   注:setState({...newState})當state爲Object、Arrary 時diff 比較的是引用,不會刷新UI 。須要使用 concat /slice /...運算符等產生新引用的方法。

  三、應用場景:

      大部分組件的工做應該是從props裏取數並渲染出來,可是當須要 用戶輸入、服務器請求、延定時變化 等做出響應。

      一般在有狀態state的組件中處理用戶交互邏輯,並經過props傳遞給子組件(一般爲無狀態組件)中。

  四、那些屬性應該用state

      state 中應該保存可能被事件處理器改變並觸發用戶頁面更新的數據。

  五、哪些屬性不該該存儲在state中

      5-一、計算所得數據。計算數據應該在render()中實現,若是存儲在state中須要手動更新state 比較麻煩

      5-二、基於props 的重複數據。組件中應該保持props爲惟一的數據來源,除非須要知道歷史數據是啥。

      5-三、不要將React組件保存在state中。在render()裏使用props、state來建立他。

  總結:state讓你修改(不修改的數據別往state存)。props不讓你修改。多個state、props共同影響UI 的時在render()中實現。

相關文章
相關標籤/搜索