【问题标题】:Cannot call callback functions on setState in componentDidMount ?? - React无法在 componentDidMount 的 setState 上调用回调函数?? - 反应
【发布时间】:2016-07-01 23:03:13
【问题描述】:

考虑以下简单代码:

  componentDidMount() {
    this._fetchData();
  }

  _fetchData() {
    let url = UrlFormatter() + '/api/v1/blogs/';

    $.get(url, (result) => {
      if (result.status === 401) {
        this.setState({
          error: 'Your session has expired. We cannot load data.',
        });
      } else {
        console.log('obvs here');
        this.setState({
          error:             null,
          data:              result,
        }, () => {
          console.log('dasddsa');
          this._setUpPostCollapseStatus();
        });
      }
    }).fail((response) => {
      this.setState({
        error: 'Could not fetch blogs, something went wrong.'
      });
    });
  }

如果我们调查我们看到的控制台:

obvs here

但我们从来没有看到:dasddsa,现在要么这是一个错误,要么你不能在 componentDidMount 中调用 setState 上的回调函数 - 或者我在 ES6 上失败了。

想法?

【问题讨论】:

  • 组件是否正确重新渲染或重新渲染时出现错误?因为回调只在重新渲染后执行

标签: javascript reactjs


【解决方案1】:

嗯,我无法复制这个;不确定这是否会有所帮助,但这里有一个解决componentDidMount 中的承诺并使用setState 回调的示例:

http://codepen.io/mikechabot/pen/dXWQAr?editors=0011

承诺

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve('Fetched data!')
  }, 2000)
})

组件

  componentDidMount() {
    console.log('Mounting...');
    promise
      .then((data) => {
        this.setState({ data }, () => {
          console.log('Data loaded')
        })
      })
      .catch(error => {
        console.log('Error', error);
      })
  }

控制台

> "Mounting..."
> "Data loaded"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 2019-01-23
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    相关资源
    最近更新 更多