React 状态不会立即更新。我想在按下“播放”按钮后立即更新状态。
import * as React from "react";
import { Button } from "react-native";
export default function Play() {
const [player, setPlayer] = React.useState(1);
function nextPlayer() {
setPlayer(2);
updateValue();
}
function updateValue() {
if (player == 1) {
console.log("player 1");
} else if (player == 2) {
console.log("player 2");
}
}
return <Button title="play" onPress={nextPlayer} />;
}
功能updateValue
是在包含您的状态的“旧值”的闭包中创建的。如果您希望它以新值运行,请使用useEffect
挂钩或传递当前值作为参数。
const [value, setValue] = useState();
useEffect(() => {
// receives the latest value and is called on every change (also the first one!)
}, [value])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)