不要在render的函數(shù)中綁定值
not: <Com onClick={() =>?this.handleClick(param)} />
會(huì)導(dǎo)致每次父組件render方法被調(diào)用時(shí),一個(gè)新的函數(shù)被創(chuàng)建。這會(huì)有一個(gè)改變每個(gè)子組件props的副作用,它將會(huì)造成它們?nèi)恐匦落秩?,即使?shù)據(jù)本身沒有發(fā)生變化。
√ :?<Com? onClick={this.handleClick} param={param} />
子組件中 handleClick() {? ? this.props.onClick(this.props.param)? ? }
不要在render方法里派生數(shù)據(jù)
not : 在render方法中
const?{ datas } =?this.props
const?data = datas.sort( (a, b) =>?b.values - a.values?).slice(0,?9)
每次組件重新渲染時(shí)data都將有一個(gè)新的引用,即使datas沒有改變并且派生數(shù)據(jù)也是相同的。
√ : 緩存派生數(shù)據(jù)
componentWillMount() {? ? this.setDatas( this.props.datas?)? ? }
componentWillReceiveProps(nextProps) {? ? if?(this.props.datas?!== nextProps.datas?) {? ? this.setDatas?(nextProps)? ? }? ? }
setDatas?(datas) {? ? this.setState({? ? datas?: datas.sort( (a, b) =>?b.values?- a.values?).slice(0,?9)? ? })? ? }