Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应:是否可以通过将this.setState设置为empty函数来防止卸载后的状态更新?_Javascript_Reactjs - Fatal编程技术网

Javascript 反应:是否可以通过将this.setState设置为empty函数来防止卸载后的状态更新?

Javascript 反应:是否可以通过将this.setState设置为empty函数来防止卸载后的状态更新?,javascript,reactjs,Javascript,Reactjs,我面临的问题是,网络回调试图设置未安装组件的state(),并收到有关此no-op的默认控制台警告 我无法跟踪卸载发生的原因,但我找到了一个解决方案,建议在componentWillUnmount()中将函数设置为nothing。它不起作用,我测试将this.setState设置为nothing。见下文 错误消失了,但我想问这是否是一个有效的解决方案。代码如下: componentDidMount() { this.fetchLogItems(10, 'recentChanges')

我面临的问题是,网络回调试图设置未安装组件的state(),并收到有关此no-op的默认控制台警告

我无法跟踪卸载发生的原因,但我找到了一个解决方案,建议在componentWillUnmount()中将函数设置为nothing。它不起作用,我测试将this.setState设置为nothing。见下文

错误消失了,但我想问这是否是一个有效的解决方案。代码如下:

  componentDidMount() {
    this.fetchLogItems(10, 'recentChanges');
  }

  componentWillUnmount() {
    this.setState = () => {};
  }

  fetchLogItems = (limit, stateRef) => {
    let tmpObj = {};
    base.fetch('_changelogs', {
      context: this,
      then(data) {
        tmpObj[stateRef] = {...data}
        tmpObj.loading = false;
        this.setState({...tmpObj})
      },
      catch(err){console.error(err)}
    });
  };
两种选择:

  • 请确保您正在使用的任何帮助程序也允许使用“析构函数”(取消,我当然更喜欢使用“取消”)
  • 如果没有,那么你可以在你的班级中引入一个“标志”
如果您的库允许一些“取消”、“销毁”或“清理”,那么您只需执行以下操作:

componentWillUnmount() {
  base.cancelFetch(); // or something similar.
}
否则,您可以向组件引入类属性。也许将其命名为
isUnmounted
。在
componentWillUnmount
中,将
this.isUmounted
设置为true。将
this.setState
调用包装在一个
if
-语句中,该语句检查
是否已卸载
为false,如果为false,则可以调用
this.setState
。这实际上是一种非常常见的模式

它可能“感觉”丑陋,但实际上,这种模式在React开发人员中似乎是惯用的。如果不是,至少这是一个务实的解决方案,类似于你的问题

constructor() {
  // HERE
  this.isUmounted = false;
}

componentDidMount() {
  this.fetchLogItems(10, 'recentChanges');
}

componentWillUnmount() {
  // HERE
  this.isUmounted = true;
}

fetchLogItems = (limit, stateRef) => {
  let tmpObj = {};
  base.fetch('_changelogs', {
    context: this,
    then(data) {
      tmpObj[stateRef] = {...data}
      tmpObj.loading = false;
      // WRAP THE `this.setState` here.
      if (!this.isUnmounted) {
        this.setState({...tmpObj})
      }
    },
    catch(err){console.error(err)}
  });
};
但是,我更喜欢使用支持取消的库和助手。这肯定能保证一定程度的清洁。如果不取消,我们就有可能导致内存泄漏