![](/img/trans.png)
[英]React shouldComponentUpdate() = false not stopping re-render
[英]React shouldComponentUpdate() does not prevent re-render
我正在使用下面显示的ThreeDisplay
React组件来保存WebGL / Three.js画布(画布本身不是该组件的一部分,它会通过初始化脚本附加到容器div
)。
我只希望组件在每个RUN
和UPDATE
操作之后进行更新。 这些动作由ThreeDisplay
的父组件ThreeDisplay
。
现在由于某种原因,如果最后一个动作是FADE_COLOR
或SWITCH_COLOR
,则组件也将得到更新/重新渲染。 这些操作由ThreeDisplay分派,它们由鼠标事件触发,如下面的代码所示。
我试图仅在上述操作之后使用shouldComponentUpdate()
进行更新。 但是由于某些原因,这不会阻止在每次鼠标事件时重新渲染组件。
我的应用程序/原型的完整代码可以在此存储库中找到
import React from 'react'
import {connect} from 'react-redux'
import {fadeColor, switchColor} from '../actions'
class ThreeDisplay extends React.Component {
shouldComponentUpdate(nextProps) {
const shouldUpdate =
nextProps.lastAction === 'RUN' || nextProps.lastAction === 'UPDATE'
if (!shouldUpdate) {
console.log('ThreeDisplay will not update on ' + nextProps.lastAction)
}
return shouldUpdate
}
componentWillUpdate() {
// This gets logged even if lastAction ist not 'RUN' or 'UPDATE'
console.log('ThreeDisplay will update on ' + this.props.lastAction)
}
render() {
return (
<div
id="container"
className={
this.props.running
? 'three-display'
: 'three-display hidden'
}
onClick={this.props.switchColor}
onMouseMove={this.props.fadeColor}
/>
)
}
}
const mapStateToProps = state => {
return {
running: state.running,
lastAction: state.lastAction
}
}
const mapDispatchTopProps = dispatch => {
return {
fadeColor: e => dispatch(fadeColor(e)),
switchColor: () => dispatch(switchColor())
}
}
export default connect(mapStateToProps, mapDispatchTopProps)(ThreeDisplay)
在这个表达中
const shouldUpdate = nextProps.lastAction === 'RUN' || 'UPDATE'
如果nextProps.lastAction === 'RUN'
为假,则代码将评估OR的另一个分支,即仅是'UPDATE'
字符串,该字符串始终为true,因此shouldUpdate
将始终为true。
替换为
const shouldUpdate = nextProps.lastAction === 'RUN'
|| nextProps.lastAction === 'UPDATE'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.