【问题标题】:value of hook not update钩子的值不更新
【发布时间】:2019-08-22 06:22:55
【问题描述】:

我有以下:

const [quantityKm, setQuantityX] = useState({ x: 0 });

我有一个范围,当它改变时会执行以下函数

const handleKmValue = (event) => {
    const { x } = event;
    setQuantityX({ x: x});
};

然后,如果我更改了<select>,则必须执行此函数

const calculatePrice = () => {
    console.log(quantityKm.x);
    setValueMonth((parseFloat(quantityKm.x.toFixed(2)) * valueOfKm))
};

但是,我总是收到 quantityKm.x 的值为 0

【问题讨论】:

  • 这是在调用什么事件?
  • 顺序和我写的一样,select 调用onChange=handleKmValue ,保存valueMonth 的值并调用fn calculatePrice,这是valueMonthquantityKm 的值0个。
  • @Mickey 是的,如果我打印 event.x 是完美的,但如果我在 setQuantityX 之后打印 quantityKm.x,则值为 0
  • 由于 setState 是异步的,如果您在调用 handleKmValue 的同一函数中调用 calculatePrice,则 calculatePrice 可能会在 quantityKm 更新之前触发。您应该将calculatePrice 移动到它自己的useEffect() 挂钩中。
  • 我是这么想的,但是我没有找到在setState运行完成后调用函数或执行代码的方法

标签: reactjs react-hooks


【解决方案1】:

从您的 cmets 看来,您的代码结构如下:

const [quantityKm, setQuantityX] = useState({ x: 0 });

const handleKmValue = ...
const calculatePrice = ...

const handleChange = event => {
    handleKmValue(event);
    calculatePrice();
}

<Select onChange={handleChange} />

改为:

const [quantityKm, setQuantityX] = useState({ x: 0 });

useEffect(() => {
    // move the calculatePrice functionality into the effect
    console.log(quantityKm.x);
    setValueMonth((parseFloat(quantityKm.x.toFixed(2)) * valueOfKm))

}, [quantityKm.x]) // run effect if value's changed

<Select onChange={handleKmValue} />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多