通常情况下,使用道具,我们可以编写
componentDidUpdate(oldProps) {
if (oldProps.foo !== this.props.foo) {
console.log('foo prop changed')
}
}
为了检测属性变化,但如果我们使用React.createRef(),如何检测引用何时更改为新的组件或DOM元素?React文档并没有真正提到任何内容。例如:class Foo extends React.Component {
someRef = React.createRef()
componentDidUpdate(oldProps) {
const refChanged = /* What do we put here? */
if (refChanged) {
console.log('new ref value:', this.someRef.current)
}
}
render() {
// ...
}
}
我们应该自己实现某种旧值功能吗?例如,class Foo extends React.Component {
someRef = React.createRef()
oldRef = {}
componentDidMount() {
this.oldRef.current = this.someRef.current
}
componentDidUpdate(oldProps) {
const refChanged = this.oldRef.current !== this.someRef.current
if (refChanged) {
console.log('new ref value:', this.someRef.current)
this.oldRef.current = this.someRef.current
}
}
render() {
// ...
}
}
这就是我们应该做的吗?我本以为React会内置一些简单的功能来实现这个。
useLayoutEffect
来确保引用不为 null。 - grabantotuseLayoutEffect
在 React 更新 DOM 后执行,因此任何引用必须在那时已更改。好的技巧。我认为这值得成为自己的答案! - trusktr