React學習開發經驗總結分享

Immutability Helper

這是react官方文檔推薦的方法(源代碼不多)
通常的state,例如層級比較淺的,能夠直接用Object.assign或者...(擴展語法來解構),可是在層級比較深,或者操做數組的狀況下reducer寫起來就要麻煩些,這時候就能夠用immutability helper的update方法了javascript

//更新數組中的某一條數據
updatePurchaseDetail(state, { index, payload }) {
      return update(state, {
        purchaseDetails: {
          [index]: {
            $merge: payload
          }
        }
      })
    },
//向數組中添加一條數據 遵循不可變數據結構 咱們不能直接用Push
addPurchaseLine(state, { item }) {
      return update(state, {
        purchaseDetails: {
          $push: [item]
        }
      })
    },
const collection = [1, 2, {a: [12, 17, 15]}];
const newCollection = update(collection, {
    2: {
      a: {
        $splice: [[1, 1, 13, 14]] // [1,1,13,14]對應於數組的splice函數的參數
      }
    }
  }
);
// => [1, 2, {a: [12, 13, 14, 15]}] 
// 在collection數組索引2的對象的a屬性的數組的索引1的位置插入13,14

考慮使用函數式的setState

react官方文檔中這樣介紹setState的html

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

setState不會當即修改this.state,也就是說咱們在調用setState的後,當即訪問this.state是不能取得最新的this.state的值的。這樣在一些特殊需求的時候可能會出現問題。可是咱們能夠經過使用setState回調函數的形式來使下面的代碼拿到最新的this.state的值。java

updateState({target}) {
   this.setState(prevState => {
     const updatedUser = {...prevState.user, [target.name]: target.value}; // 使用先前的state來構建新的state的值
     doSomething(updatedUser); 
     return { user: updatedUser }; 
   });
 }

使用PureComponent

你們都知道使用好shouldComponentUpdate 能夠優化性能,對props 和 state 的全部屬性進行比較來決定組件是否須要更新, 這個函數默認都是返回true,也就是說須要更新。當咱們嚴格遵照不可變數據結構的時候,就能夠繼承React.PureComponent來對props和state進行淺比較來決定組件是否應該更新,方便的優化咱們組件的性能。PureComponent代替咱們作了下面例子中shouldComponentUpdate函數作的事情.相關連接react

class CounterButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

使用內聯函數與傳遞props的問題

在react中使用內聯函數(在render方法裏面定義的函數,並經過props傳遞到子組件)是很方便的,可是這樣用也會影響應用的性能。
影響性能的緣由主要有兩個
1.會常常觸發垃圾回收機制
2.一個內聯函數每次都是一個新的引用,也就是說每次都會觸發子組件的render函數(這個時候使用PureComponent就無效了)webpack

class MyComponent extends React.Component {
  render() {
    const msg = "Hello " + this.props.user.name.first;
    return <PureChild onClick={() => this.props.onAlert(msg)} />;
    //另外一種形式 this.props.onAlert.bind(this, msg)
  }
}

如何避免使用inline function
1.能夠把數據綁定在元素上git

...
//同一個函數須要處理多種狀況的時候
handleClick = (ev) => {
  const { action } = ev.target.dataSet
  this.props.dispatch({
    type: 'handleBpm',
    action
  })
}
...
  <Button data-action="Approve" onClick={this.handleClick}>approve</Button>
  <Button data-action="Reject" onClick={this.handleClick}>reject</Button>

2.把事件處理函數移到子組件github

// 父組件
...
render () {
  const msg = "Hello " + this.props.user.name.first;
  return (
    <PureChild onAlert={this.props.onAlert} msg={msg} />
  )
}
// 子組件 PureChild
handleClick = () => {
  //do something
  const { onAlert, msg } = this.props;
  onAlert(msg)
}
...
render () {
  return (
    ...
    <div onClick={this.handleClick}></div>
  )
}

第二種方法須要咱們在能夠編碼子組件的狀況下才能夠作到
還有一種經過babel插件reflective-bind的方式能夠參考
不僅是內聯函數,咱們在render函數裏面應該儘量少的聲明實例,儘可能不把在render裏生成的實例當作Props傳遞下去。web

區分Container與Component

Container與Component的主要區別在於:數組

1.Container是跟全局狀態有關聯的,一般被用來管理數據並經過connect函數鏈接到全局state,幾乎不寫樣式
2.Component與樣式聯繫緊密,可是不參與管理任何數據,只經過接收到的props響應數據更改

在dva中routes下面的文件目錄至關於containers,也就是說咱們須要使用connect的組件就應該規劃在這裏面。
component文件目錄就應該放置與全局state無關,能夠複用的通用組件。babel

另外每個文件夾的入口文件能夠用index.js命名,這樣有兩個明顯的好處。第一點是可讓閱讀代碼的人,一眼就知道在當前目錄下,哪一個文件是入口文件。第二點是在其餘文件Import目標文件的時候,只須要寫到folderName的位置就能夠了。webpack會自動讀取當前文件目錄下的index文件。
例如import Home from routes/home 而不用寫成import Home from routes/home/index

關於react規範結構的問題 能夠參考
how to scale react applications
react-boilerplate
Airbnb React 編碼規範

相關文章
相關標籤/搜索