代码之家  ›  专栏  ›  技术社区  ›  Ukasha

异步等待和setTimeout在reactjs中不工作

  •  1
  • Ukasha  · 技术社区  · 7 年前

    你可以看到我做了什么 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... 首先,然后显示 Gotcha!!! 10秒后。但是,它不起作用。我犯了什么错?

    3 回复  |  直到 7 年前
        1
  •  3
  •   CertainPerformance    7 年前

    问题是:

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

    第一个论点 setTimeout 应该是 功能 . 现在,你 打电话 resolve 立即 设置超时 尝试(同步)解析其参数相反,传递一个函数 然后 电话 决定 :

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

    setTimeout(resolve, 10000, "Gotcha!!!");
    
        2
  •  1
  •   Abdullah    7 年前

    你必须通过 setTimeout 回调函数,将其更改为

    setTimeout(() => resolve("Gotcha!!!"), 10000);
    
        3
  •  1
  •   Farooq Hanif    7 年前
    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);