React使用shouldComponentUpdate跳过重渲染时nextState字段为undefined问题
问题原因分析
shouldComponentUpdate入参顺序错误
React类组件的shouldComponentUpdate生命周期函数的固定入参顺序为第一个参数是更新后的props(nextProps),第二个参数才是更新后的state(nextState),你只声明了一个参数,因此拿到的nextState实际上是父组件传入的新props,自然不存在timespanState属性,值为undefined,判断条件this.state.timespanState !== nextState.timespanState永远成立,函数始终返回true触发重渲染。业务逻辑不符合需求
你现在下拉选择变更时直接修改了timespanState,而这个状态是提供给图表组件的依赖值,哪怕你修好了shouldComponentUpdate的参数问题,只要timespanState变化,还是会触发图表组件的重渲染,不符合「点击应用按钮才更新图表」的需求。
修复方案
步骤1:拆分状态,区分临时选中值和正式生效值
新增临时状态存储下拉框的实时选中值,只有点击「应用」按钮时才更新传给图表的正式值,从根源上避免下拉选择时触发图表依赖的状态变更:
constructor(props) { super(props); this.state = { timespanState: 'Today', // 正式生效值,传给图表组件的依赖属性 tempTimespan: 'Today' // 临时选中值,仅用于下拉框交互 }; this.handleTimeSpanChange = this.handleTimeSpanChange.bind(this); this.handleApply = this.handleApply.bind(this); }
步骤2:修改下拉框绑定的状态和事件
下拉框绑定临时状态,变更时仅修改临时状态:
<Select value={this.state.tempTimespan} onChange={this.handleTimeSpanChange}>
handleTimeSpanChange = (event) => { // 仅修改临时状态,不会触发图表重渲染 this.setState({ tempTimespan: event.target.value }); };
步骤3:新增应用按钮点击逻辑
点击应用时才将临时值同步到正式状态,触发图表更新:
handleApply = () => { this.setState({ timespanState: this.state.tempTimespan }); // 此处补充图表筛选逻辑 }
步骤4:修正shouldComponentUpdate写法(如果是在图表子组件内实现)
如果shouldComponentUpdate是写在图表子组件内,判断传入的props变化即可:
shouldComponentUpdate(nextProps, nextState) { // 仅当正式的时间跨度属性变化时才更新组件 return this.props.timespanState !== nextProps.timespanState; }
内容的提问来源于stack exchange,提问作者congying pan
相关产品推荐
相关产品推荐

