簡體   English   中英

在處理來自輸入的 onChange 事件時如何獲取當前的 state?

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

我知道反應組 state 更新以提高性能,但我需要獲取當前的 state,請告訴我該怎么做?

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 [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 中的回調給出了想要的結果

像這樣:

  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 更改運行 useEffect 與 state 的依賴項將完成工作:

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

這將在每次 inputValue 更改時運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM