關于React的更組件新優(yōu)化;
**在父組件的頁面更新的時候會帶動其內(nèi)部的子組件也觸發(fā)更新,如果父組件的更新不會影響到子組件,那么多余的更新是完全沒有必要的,反而會造成不必要的性能問題;
//父組件
import React, { Component } from 'react';
import List from './List.jsx';
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
'第一列',
'第二列',
'第三列',
'第四列',
'第五列'
],
inputVal: ''
}
this.handleInput = this.handleInput.bind(this);
this.addList = this.addList.bind(this);
}
componentDidMount() {
}
render() {
return (
<div>
<input ref={input => this.input = input} value={this.state.inputVal} onChange={this.handleInput} />
<List list={this.state.list}></List>
<button onClick={this.addList}>點擊按鈕</button>
</div>
);
}
handleInput(ev) {
this.setState({ inputVal: ev.target.value });
}
addList(ev) {
this.setState({ list: [...this.state.list, this.input.value] });
}
}
export default App;
//子組件
import React, { Component, Fragment } from 'react';
class List extends Component {
constructor(props) {
super(props);
}
//控制組件是否更新的生命周期函數(shù),必須返回一個boolean對象;true為更新,false為不更新
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.list == this.props.list) {
return false;
}
return true;
}
render() {
return (
<Fragment>
<ul>
{
this.props.list.map((item, key) => {
return (
<li key={key + item}>{item}</li>
)
})
}
</ul>
</Fragment>
);
}
}
export default List;