如何使用shouldComponentUpdate状态?
shouldComponentUpdate
我可以检查:
shouldComponentUpdate(nextProps, nextState) { return this.state.value != nextState.value; }
但这对国家没有任何意义。因为如果我改变state(this.setState({value: 'newValue'}))this.state将会相等 nextState。
this.setState({value: 'newValue'})
this.state
nextState
例如,onClick事件:
onClick
handleClick() { this.setState({value: 'newValue'}); }
该shouldComponentUpdate(nextProps, nextState)方法适用于道具和状态。在您的示例中,onClick事件发生后,React将触发以下方法。
shouldComponentUpdate(nextProps, nextState)
关键是在上述方法中,的值this.state.value等于调用 前 的值setState()。这要归功于在React中:
this.state.value
setState()
setState()不会立即更改this.state,但会创建一个挂起的状态转换。 反应文档:https : //facebook.github.io/react/docs/component- api.html#setstate
看一下这个演示:http : //codepen.io/PiotrBerebecki/pen/YGZgom(下面的完整代码)
React保持状态,即每次单击按钮的次数,并保存随机选择的value(true或false)。但是,由于采用了这种 shouldComponentUpdate方法,只有当前 一个 value不等于即将到来的/ new时,才重新渲染组件value。这就是为什么显示的点击计数有时会跳过呈现其当前状态的原因。您可以注释掉整个shouldComponentUpdate方法,以在每次单击时重新呈现。
value
class App extends React.Component { constructor() { super(); this.state = { value: true, countOfClicks: 0 }; this.pickRandom = this.pickRandom.bind(this); } pickRandom() { this.setState({ value: Math.random() > 0.5, // randomly picks true or false countOfClicks: this.state.countOfClicks + 1 }); } // comment out the below to re-render on every click shouldComponentUpdate(nextProps, nextState) { return this.state.value != nextState.value; } render() { return ( <div> shouldComponentUpdate demo <p><b>{this.state.value.toString()}</b></p> <p>Count of clicks: <b>{this.state.countOfClicks}</b></p> <button onClick={this.pickRandom}> Click to randomly select: true or false </button> </div> ); } } ReactDOM.render( <App />, document.getElementById('app') );