简体   繁体   English

输入值 onChange - React Hooks

[英]Input value onChange - React Hooks

I'm trying to collect the value typed in a input box, but when I use onChange I can only get the previous value.我正在尝试收集在输入框中键入的值,但是当我使用 onChange 时,我只能获得以前的值。 For example after I just typed "text" the latest value to be collected would be "tex"例如,在我刚刚输入“text”之后,要收集的最新值将是“tex”

import React, {useState} from 'react';
import './SearchBar.css';

const SearchBar = (props) => {

    const [input, setInput] = useState('');

    const onChange = (e) => {
        setInput(e.currentTarget.value);
        console.log(input);
    }

    let sugestionList = (
        <ul>
            <li>item 1</li>
            <li>item 2</li>
        </ul>
    )



    return(
        <div className="search-bar">
            <input type="text" placeholder={props.placeholder} onChange={onChange}/>
            {sugestionList}
        </div>

    )
}

That's because updating a state is an asynchronous task.那是因为更新状态是一项异步任务。 To get the latest state you can use useEffect() hook.要获取最新状态,您可以使用useEffect()钩子。

useEffect(() => {console.log("input state is", input)}, [input]) //add the state in dependency array and this useEffect will run whenever state changes//

It's happening because updating state is asynchronous and you are checking(console.log) in the same onChange function that's why it's not giving proper input value but it's working/updating properly.这是因为更新状态是异步的,并且您正在同一个onChange函数中检查 (console.log) 这就是为什么它没有提供正确的输入值但它正在正常工作/更新的原因。

instead of doing console inside onChange you can check here -而不是在onChange里面做控制台,你可以在这里检查 -

const onChange = (e) => {
   setInput(e.currentTarget.value);
  }
  console.log(input)
  return(
      <div className="search-bar">
          <input type="text" placeholder={'props.placeholder'} onChange={onChange}/>
          {sugestionList}
      </div>
  )

another solution is using useEffect as already posted one solution by Atin.另一种解决方案是使用useEffect作为已经由useEffect发布的一个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM