我已阅读isMounted is an Antipattern并且仍然不确定下面的代码在使用回调时是否会导致内存泄漏?
class MyComponent extends React.Component {
componentDidMount() {
this.mounted = true
}
componentWillUnmount() {
this.mounted = false
}
someAPIcall() {
callSomething(argument, (err, result) => {
if (this.mounted === false) return
// otherwise do something
this.setState({...})
})
}
}
答案 0 :(得分:1)
最好这样做:
class MyComponent extends React.Component {
componentDidMount() {
someAPIcall();
}
someAPIcall() {
callSomething(argument, (err, result) => {
this.setState({...})
})
}
}