如何处理才能在runPromise2上读取的count值是1?
import React, {useState} from "react";
export default () => {
const [count, setCount] = useState(0)
const runPromise1 = () => {
return new Promise((resolve) => {
setTimeout(() => { // 异步action
setCount(() => {
console.log(1)
return 1
})
resolve('ok')
}, 2000)
})
}
const runPromise2 = (msg) => {
console.log(count) // count => 0
const promise = Promise.resolve('hello ')
return promise.then(data => {
console.log(data + msg)
})
}
const onClick = () => {
runPromise1().then(runPromise2)
}
return (
<div className="p20">
<button onClick={onClick}>点击</button>
<h1>{count}</h1>
</div>
);
};
这是因为这里的setCount是异步的,用useRef转一次才能保证下面获取到正确的count,如果你不用function写法,换成setState,它的第二个参数就是回调。下面是例子:
https://codesandbox.io/s/reac...