【问题标题】:React setstate does not work in IE unless timeout is used除非使用超时,否则 React setstate 在 IE 中不起作用
【发布时间】:2019-09-19 20:03:14
【问题描述】:

我有以下方法,使用 whatwg-fetch 进行服务调用。 setstate 不适用于 IE 浏览器。它适用于其他浏览器。

在 settimeout 中包含 setstate 后,它在 IE 中运行良好。

不确定此超时是否会影响它在产品服务器中的部署以及响应时间延迟的增加。请建议我为这个问题提供一个理想的解决方案。谢谢!

        fetch("/local/addThings").then(res => res.json())
            .then(
                (result) => {
                 setTimeout(() => {
                    this.setState({
                        value: "edit",
                        items: result
                    });
                     }, 1000);
                       }
            )
            .catch(error => console.error('Error:', error));
    }```

【问题讨论】:

    标签: reactjs timeout internet-explorer-11 setstate


    【解决方案1】:

    这可能是因为获得结果的时间延迟。您可以在设置状态之前放入条件语句以检查是否已收到结果。

    fetch("/local/addThings").then(res => res.json())
      .then(
        (result) => {
          if (result) {
            this.setState({
              value: "edit",
              items: result
            });
          }
        } else {
          setTimeout(() => {
            this.setState({
                value: "edit",
                items: result
            });
             }, 1000);
        }
      )
      .catch(error => console.error('Error:', error));
    }
    

    我还注意到您有两个 .then 语句。如果你用第一个这样设置状态呢?

    fetch("/local/addThings")
      .then(res => 
        this.setState({
          value: "edit",
          items: res
        })
      )
      .catch(error => console.error('Error:', error));
    }
    

    【讨论】:

      【解决方案2】:

      这可能与 setState 异步有关:

      您可以尝试删除 setTimeout 并给 setState 一个函数而不是一个对象,如下所示:

      this.setState(() => ({
        value: "edit",
        items: result
      }));
      

      【讨论】:

        【解决方案3】:

        这是因为在 React 中调用 setState() 是异步的,它并不总是立即更新组件。请查看official documentation 关于setState()

        您可以使用componentDidUpdatesetState 回调(setState(updater, callback)),保证在应用更新后会触发其中任何一个。我们只需要在回调中获取更新的状态:

        this.setState({ value: "edit", items: result },()=>{
            console.log(this.state.value); //any function u want to call after state changed
        });
        

        【讨论】:

        • 我的场景是我需要从 api 调用中获取结果并根据通过 result 返回的值进行渲染。所以它反过来。我需要 api 调用的结果,然后需要根据结果设置状态。
        • setState() 将始终导致重新渲染,除非 shouldComponentUpdate() 返回 false。您可以参考this thread 了解更多信息。你也可以参考this article关于强制react组件渲染。
        猜你喜欢
        • 2013-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-27
        相关资源
        最近更新 更多