异步等待和setTimeout在ReactJS中不起作用

时间:2018-07-21 04:47:20

标签: javascript reactjs async-await

您可以看到我所做的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!!!。但是,它不起作用。我怎么了?

3 个答案:

答案 0 :(得分:3)

问题是:

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

setTimeout的第一个参数应该是 function 。目前,您{em}正在{em}调用{em} resolve,因为setTimeout试图(同步)解析其参数。而是给它传递一个 then 调用resolve的函数:

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

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

答案 1 :(得分:1)

您需要传递setTimeout回调函数,并将其更改为此

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

答案 2 :(得分:0)

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);