关于React的更组件新优化;
**在父组件的页面更新的时候会带动其内部的子组件也触发更新,如果父组件的更新不会影响到子组件,那么多余的更新是完全没有必要的,反而会造成不必要的性能问题;
//父组件
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);
}
//控制组件是否更新的生命周期函数,必须返回一个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;