有这样一个组件结构:
|-- div
| |-- Group1
| | |-- Input1
| | |-- Input2
| |-- Group2
| | |-- Input3
| | |-- Input4
我在触发修改 Input1 的时候,会导致 render 所有的组件:
[Render Group]
[Render Input] flag: 1
[Render Input] flag: 2
[Render Group]
[Render Input] flag: 3
[Render Input] flag: 4
请问如何避免呢,比如我在修改 Input1时候,仅渲染 Input1,其余不重新渲染?
问题代码如下:
class App extends Component {
constructor (props) {
super(props)
this.state = {
val1: '',
val2: '',
val3: '',
val4: ''
}
}
handleInput (flag, val) {
const key = 'val' + flag
this.setState({ [key]: val })
}
render () {
return (
<div className="App">
<Group name="Group1">
<Input flag="1" onChange={v => this.handleInput.call(this, 1, v)}/>
<Input flag="2" onChange={v => this.handleInput.call(this, 2, v)}/>
</Group>
<Group name="Group2">
<Input flag="3" onChange={v => this.handleInput.call(this, 3, v)}/>
<Input flag="4" onChange={v => this.handleInput.call(this, 4, v)}/>
</Group>
</div>
)
}
}
class Group extends Component {
render () {
console.log('[Render Group]')
const children = this.props.children
return (
<div>
<h1>{this.props.name}</h1>
{
React.Children.map(children, child => child)
}
</div>
)
}
}
class Input extends Component {
constructor (props) {
super(props)
this.state = {
value: ''
}
}
handleChange (e) {
const cb = this.props.onChange
const value = e.target.value
this.setState({ value })
cb && cb(value)
}
render () {
console.log('[Render Input] flag:', this.props.flag)
return (
<div>
<input value={this.state.value} onChange={e => this.handleChange.call(this, e)}/>
</div>
)
}
}
你的子组件在更新自身状态的同时,也更新了父组件的状态,就是
cb && cb(value)
这行代码。在react中,父组件更新,默认是会更新所有子组件、孙组件的。
这种情况下,你必须重写
shouldComponentUpdate
方法,自行判断这个组件是否需要更新,return false
就会阻止更新