从输入处理 onChange 事件时如何获取当前状态?

How to get the current state when processing the onChange event from an input?

我知道反应组状态更新以提高性能,但我需要获取当前状态,请告诉我该怎么做?

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [inputValue, setInputValue] = useState("");
  const handleChange = e => {
    
    console.log(e.target.value, 'here is the desired state');
    setInputValue(e.target.value,'but here is always one step behind');
    console.log(inputValue); // I am outputting the log from the handler and this is not true. The state has changed and there is no error.
  };
  return (
    <div className="App">
      <input type="text" value={inputValue} onChange={handleChange} />
    </div>
  );
}

https://codesandbox.io/s/react-onchange-3pond?file=/src/App.js:0-407

像这样:

  const handleChange = e => {

    console.log(e.target.value, 'here is the desired state');
    setInputValue(currentSate=>console.log(currentSate)); here you have access to current sate
    console.log(inputValue);
  };

如果你想访问 newState 更改 运行ning useEffect 与该状态的依赖关系将完成工作:

useEffect(()=>console.log(inputValue),[inputValue])

每次 inputValue 更改时都会 运行。

折腾了很久,我发现我可以这样做

  const [inputValue, setInputValue] = useState('')

  useEffect(() => {
    onSearch(inputValue)
  }, [inputValue, onSearch])

  const onInputChange = (e) => {
    const value = e.target.value

    setInputValue(value)

    console.log('state', inputValue);

  }

  return (
    <div className={style.wrapper}>
      <FilterPanel onFilterItems={onFilterItems} stateFilter={stateFilter} />

      <input
        type="text"
        value={inputValue}
        onChange={onInputChange}
        className={style.input}
        placeholder="search"
      />
    </div>
  )

useEffect 中的回调给出了想要的结果