【问题标题】:How to use setState in an asynchronous function如何在异步函数中使用 setState
【发布时间】:2018-01-06 15:10:36
【问题描述】:

我正在运行这段代码:

.then((url) => {
      if (url == null || undefined) {
          return this.props.image;
      } else {

          const { image } = this.props;

          //entryUpdate is an action creator in redux.
          this.props.entryUpdate({ prop: 'image', value: url })
               .then(() => {
                   this.setState({ loading: false });
               });

但我收到以下错误:

如何在动作创建者之后调用的异步函数中格式化 setState()?

任何帮助将不胜感激!

【问题讨论】:

  • 看起来this.props.entryUpdate 函数没有返回promise
  • 是的,我想通了。我把 .then() 函数放得太早了。感谢您的帮助!

标签: reactjs asynchronous react-native redux-thunk setstate


【解决方案1】:

为了使其正常工作,您的动作创建者this.props.entryUpdate 需要为其正在执行的异步工作返回一个承诺。查看错误消息,目前似乎并非如此。

您还需要注意,当 promise 解决时组件已经卸载时,在异步回调中调用 setState() 可能会导致错误。

一般更好的方法可能是使用componentWillReceiveProps等待新值流入组件,然后触发setState

【讨论】:

    【解决方案2】:

    我将 .then() 函数放在 if 语句中。但应该是这样的:

    .then((url) => {
        if (url == null || undefined) {
          return this.props.image;
        } else {
          const { image } = this.props;
          this.props.entryUpdate({ prop: 'image', value: url })
        }
     })
            .then(() => {
                this.setState({ loading: false });
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2020-05-05
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      相关资源
      最近更新 更多