无法让功能组件中的异步代码表现得像 class 组件
Can't get async code in functional component to behave like class component
我在新的 create-react-app 中将下面的代码添加到 App.js(功能组件)。出于某种原因,sleep() 没有增加我正在寻找的延迟。
useEffect(() => {
async function sleep() {
await new Promise(resolve => setTimeout(resolve, 2000));
}
console.log("sleep start");
sleep();
console.log("sleep done");
}, []);
为了测量延迟,我使用以下方法:
console.logCopy = console.log.bind(console);
console.log = function(data) {
var currentDate = "[" + new Date().toUTCString() + "] ";
this.logCopy(currentDate, data);
};
类似的异步代码在 App.js 的 class 版本中工作得很好:
async componentDidMount() {
console.log("sleep start");
await new Promise(resolve => setTimeout(resolve, 2000));
console.log("sleep done");
}
因为useEffect是同步的,应该在async body里面,例如:
useEffect(() => {
async function sleep() {
console.log("sleep start");
await new Promise(resolve => setTimeout(resolve, 2000));
console.log("sleep done");
}
sleep();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
我在新的 create-react-app 中将下面的代码添加到 App.js(功能组件)。出于某种原因,sleep() 没有增加我正在寻找的延迟。
useEffect(() => {
async function sleep() {
await new Promise(resolve => setTimeout(resolve, 2000));
}
console.log("sleep start");
sleep();
console.log("sleep done");
}, []);
为了测量延迟,我使用以下方法:
console.logCopy = console.log.bind(console);
console.log = function(data) {
var currentDate = "[" + new Date().toUTCString() + "] ";
this.logCopy(currentDate, data);
};
类似的异步代码在 App.js 的 class 版本中工作得很好:
async componentDidMount() {
console.log("sleep start");
await new Promise(resolve => setTimeout(resolve, 2000));
console.log("sleep done");
}
因为useEffect是同步的,应该在async body里面,例如:
useEffect(() => {
async function sleep() {
console.log("sleep start");
await new Promise(resolve => setTimeout(resolve, 2000));
console.log("sleep done");
}
sleep();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);