[英]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.