[英]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.