簡體   English   中英

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

[英]Async await and setTimeout are not working in ReactJS

您可以在這里看到我的工作。

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秒后。 但是,它不起作用。 我怎么了

問題是:

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

setTimeout的第一個參數應該是一個函數 目前,您正在立即調用 resolve ,因為setTimeout嘗試(同步)解析其參數。 而是給它傳遞一個函數, 然后調用resolve

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

要么

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

您需要通過setTimeout一個回調函數,將其更改為此

setTimeout(() => resolve("Gotcha!!!"), 10000);
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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM