Обычно, с помощью реквизита, мы можем написать
componentDidUpdate(oldProps) {
if (oldProps.foo !== this.props.foo) {
console.log('foo prop changed')
}
}
, чтобы обнаружить изменения реквизита.
Но если мы используем React.createRef()
, как мы можем определить, когда ссылка измениласьк новому компоненту или элементу DOM?Документы по React ничего не упоминают.
Fe,
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() {
// ...
}
}
Должны ли мы сами реализовывать что-то вроде старой ценности?
Fe,
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 приготовил бы для этого какую-нибудь простую функцию.