【问题标题】:Async await and setTimeout are not working in ReactJS异步等待和 setTimeout 在 ReactJS 中不起作用
【发布时间】:2018-07-21 13:10:17
【问题描述】:

你可以看到我做了什么here

import "babel-polyfill";
import React from "react";
import ReactDOM from "react-dom";

const asyncFunc = () => {
  return new Promise(resolve => {
    setTimeout(resolve("Gotcha!!!"), 10000);
  });
};

class App extends React.Component {
  state = {
    text: "Fetching..."
  };

  componentDidMount = async () => {
    const text = await asyncFunc();
    this.setState({ text });
  };

  render() {
    return <div className="App">{this.state.text}</div>;
  }
}

应用应首先显示 Fetching...,然后在 10 秒后显示 Gotcha!!!。但是,它不起作用。我的错误是什么?

【问题讨论】:

    标签: javascript reactjs async-await


    【解决方案1】:

    问题是:

    setTimeout(resolve("Gotcha!!!"), 10000);
    

    setTimeout 的第一个参数应该是一个函数。目前,您调用 resolve 立即setTimeout 尝试解析其参数(同步)。相反,向它传递一个然后调用resolve的函数:

    setTimeout(() => resolve("Gotcha!!!"), 10000);
    

    setTimeout(resolve, 10000, "Gotcha!!!");
    

    【讨论】:

      【解决方案2】:

      需要给setTimeout传一个回调函数,改成这个

      setTimeout(() => resolve("Gotcha!!!"), 10000);
      

      【讨论】:

        【解决方案3】:
        import "babel-polyfill";
        import React from "react";
        import ReactDOM from "react-dom";
        
        import "./styles.css";
        
        const asyncFunc = () => {
          return new Promise(resolve => {
            setTimeout(() => resolve("Gotcha!!!"), 10000);
          });
        };
        
        class App extends React.Component {
          constructor() {
            super();
            this.state = {
              text: "Fetching..."
            };
          }
        
          componentDidMount = async () => {
            const newText = await asyncFunc();
            this.setState({ text: newText });
          };
        
          render() {
            return <div className="App">{this.state.text}</div>;
          }
        }
        
        const rootElement = document.getElementById("root");
        ReactDOM.render(<App />, rootElement);
        

        【讨论】:

          猜你喜欢
          • 2023-04-07
          • 2018-01-02
          • 2019-08-08
          • 2019-03-17
          • 2018-01-27
          • 2019-01-09
          • 1970-01-01
          相关资源
          最近更新 更多