是否应该在组件卸载时清除 React 组件方法引用?
Should React component method reference be cleared in component unmount?
让我们假设一些事情是这样的:
handleClick = () => {
dispatchThunkAction(this.someMethod),
}
someMethod = () => {
//do something
}
dispatchThunkAction
触发 http 请求。
完成后,thunk 操作会回调 someMethod
传递给它的内容。
是否应该在 componentWiUnmount
中将 someMethod
设置为 null
,因为卸载发生在 http(或任何其他异步操作)调用的中间?
所以,喜欢
componentWillUnmount() {
this.someMethod = null;
}
以便垃圾收集器知道它可以立即将其捡起。
将方法设置为 null
将无济于事,但您可以创建一个实例变量,例如_isMounted
您在 componentDidUnmount
中设置为 false
并在 someMethod
.
中执行任何操作之前检查此变量是否为 true
class App extends React.Component {
_isMounted = true
handleClick = () => {
dispatchThunkAction(this.someMethod)
}
someMethod = () => {
if (!this._isMounted) {
return
}
//do something
}
componentDidUnmount() {
this._isMounted = false
}
// ...
}
让我们假设一些事情是这样的:
handleClick = () => {
dispatchThunkAction(this.someMethod),
}
someMethod = () => {
//do something
}
dispatchThunkAction
触发 http 请求。
完成后,thunk 操作会回调 someMethod
传递给它的内容。
是否应该在 componentWiUnmount
中将 someMethod
设置为 null
,因为卸载发生在 http(或任何其他异步操作)调用的中间?
所以,喜欢
componentWillUnmount() {
this.someMethod = null;
}
以便垃圾收集器知道它可以立即将其捡起。
将方法设置为 null
将无济于事,但您可以创建一个实例变量,例如_isMounted
您在 componentDidUnmount
中设置为 false
并在 someMethod
.
true
class App extends React.Component {
_isMounted = true
handleClick = () => {
dispatchThunkAction(this.someMethod)
}
someMethod = () => {
if (!this._isMounted) {
return
}
//do something
}
componentDidUnmount() {
this._isMounted = false
}
// ...
}