【问题标题】:How to get the current state when processing the onChange event from an input?处理来自输入的 onChange 事件时如何获取当前状态?
【发布时间】:2020-06-07 00:20:27
【问题描述】:

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

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

【问题讨论】:

  • 不使用onchange?改为听向上或向下键?
  • setInputValue() 是异步的,因为所有状态设置都在 React 中。您可以使用useEffect() 跟踪更改
  • @evolutionxbox 我需要一个受控组件,向上或向下键不会改变输入值
  • 什么落后了一步?
  • 当前状态 - inputValue dropbox.com/s/72f28hppiu1k4oy/…

标签: javascript reactjs setstate


【解决方案1】:

经过一番折腾,我意识到我可以这样做

  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 中的回调给出了想要的结果

【讨论】:

    【解决方案2】:

    像这样:

      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 与该状态的依赖关系将完成工作:

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

    这将在每次 inputValue 更改时运行。

    【讨论】:

    • 不会设置新值
    猜你喜欢
    • 2020-01-10
    • 2016-01-20
    • 2021-04-07
    • 2020-07-12
    • 1970-01-01
    • 2020-09-04
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多