Brothers please help me with a question
First look at the code I wrote
import React, {useState} from 'react';
export default function MyComponent() {
const [status, setStatus] = useState(0);
// 点击按钮时切换status的值
const click = (val) => {
setStatus(val);
getStatus()
};
// 打印最新的status值
const getStatus = () => {
console.log(status);
};
return (
<div style={
{ marginLeft: '20px' }}>
<h2>{status}</h2>
<button onClick={() => click(1)}>按钮1</button>
<button onClick={() => click(2)}>按钮2</button>
<button onClick={() => click(3)}>按钮3</button>
</div>
);
}
Encountered a problem to print the value of status in the getStatus function, what he prints is always the old value
For example: now the value of status is 0, I click "button 1", the value of status is displayed as 1, no problem, but I call the getStatus function after clicking the button, the value of status is printed in the function, and the result is printed as 0
I know the reason for the problem is that setStatus is an asynchronous operation, but I don't know how to solve it
I tried using setTimeout in click but it didn't work
const click = (val) => {
setStatus(val);
setTimeout(getStatus, 0);
};
Also used the callback when the status changes
useEffect(() => {
getStatus();
}, [status]);
This will cause me to click button 1 for the second time, and the getStatus function will not be triggered
Of course, I must know that the getStatus function receives parameters and it’s over. Pass the val value to getStatus in click, and then print it. If this is the case, why should I write another function? I directly in clikc Can't print it
I'm just elaborating on the problem! ! !
I hope there is a big guy who can help, save me, this little rookie