[英]Async await and setTimeout are not working in ReactJS
You can see what I've done 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>;
}
}
The app should show Fetching...
first, then shows Gotcha!!!
该应用程序应首先显示Fetching...
,然后显示Gotcha!!!
after 10 seconds. 10秒后。 But, it's not working. 但是,它不起作用。 What's my mistake? 我怎么了
The problem is: 问题是:
setTimeout(resolve("Gotcha!!!"), 10000);
The first argument to setTimeout
should be a function . setTimeout
的第一个参数应该是一个函数 。 At the moment, you're calling resolve
immediately as setTimeout
tries to resolve its arguments (synchronously). 目前,您正在立即调用 resolve
,因为setTimeout
尝试(同步)解析其参数。 Instead, pass it a function that then calls resolve
: 而是给它传递一个函数, 然后调用resolve
:
setTimeout(() => resolve("Gotcha!!!"), 10000);
or 要么
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.