为什么挂钩值与事件目标值不同?

时间:2019-09-09 17:13:53

标签: reactjs

我有一个输入,当它的值更改时,我将其记录下来,但是当我在输入中键入“ John”时,“ e.target.value” =“ John”,而“ searchInputValue” =“ Joh”, 似乎“ searchInputValue”总是缺少最后一个字母, 我如何才能真正获得与searchInputValue相同的e.target.value?

const [searchInputValue, setSearchInputValue] = useState("");

function handleChange(e) {
  setSearchInputValue(e.target.value);
  console.log("target value ", e.target.value); <- return the good value
  console.log("searchValue ", searchInputValue); <- return the value without 
  the last letter typed
}

<input
  type="text"
   onChange={e => handleChange(e)}
/>

有人可以帮助我吗?谢谢

2 个答案:

答案 0 :(得分:2)

setSearchInputValue是异步的,您还将在下一个渲染中获得新状态。这就是您不会立即看到它的原因。

此外,您需要对输入进行控制。

<input
  type="text"
  value = {searchInputValue}
   onChange={e => handleChange(e)}
/>

答案 1 :(得分:2)

当我尝试使用React Hooks时遇到了同样的问题。这里缺少的基本概念是“ setSearchInputValue”是一个异步函数。

要获取更新的值,请使用“ useEffect”挂钩。

    useEffect(() => {
     console.log("searchValue ", searchInputValue);
  },[searchInputValue]);