React js componentWillUnmount用于回调

时间:2016-04-08 11:24:25

标签: reactjs

我已阅读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({...})         
    })
  }
}

1 个答案:

答案 0 :(得分:1)

最好这样做:

class MyComponent extends React.Component {
  componentDidMount() {
    someAPIcall();
  }

  someAPIcall() {
    callSomething(argument, (err, result) => {

      this.setState({...})         
    })
  }
}