【问题标题】:React state not updating immediately反应状态没有立即更新
【发布时间】:2021-02-15 14:07:18
【问题描述】:

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} />;
}

【问题讨论】:

  • 你能澄清一下你应该做什么吗?
  • 您可以使用```multiline-code-here````putting them inside ticks` 的单个项目来格式化您的代码。真的很有帮助。

标签: reactjs react-native use-state


【解决方案1】:

函数updateValue 是在包含您状态的“旧值”的闭包中创建的。如果您希望它使用新值运行,请使用 useEffect 挂钩或将当前值作为参数传递。

const [value, setValue] = useState();

useEffect(() => {
  // receives the latest value and is called on every change (also the first one!)
}, [value])

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多