最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React state one step behind after set state - Stack Overflow

programmeradmin7浏览0评论

I have an input field which has an OnChange function handler to update valA. However the console does not log the changed value after I call the setState for valA - it is one step lagged behind

How can i get it to log the new input?

function test( props ){

const { valA, setValA } = props

function handleOnChange( e ){
    
    var newValA = e.target.value
    setValA(newValA)
    console.log(valA)

    return( null )

}
return( null )



}

I have an input field which has an OnChange function handler to update valA. However the console does not log the changed value after I call the setState for valA - it is one step lagged behind

How can i get it to log the new input?

function test( props ){

const { valA, setValA } = props

function handleOnChange( e ){
    
    var newValA = e.target.value
    setValA(newValA)
    console.log(valA)

    return( null )

}
return( null )



}
Share Improve this question asked Mar 13, 2021 at 9:17 Dudey007Dudey007 1052 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You will need to watch your updated state using useEffect:

function handleOnChange() { // your logic }

useEffect(() => {
  console.log(valA);
}, [valA]);

The code you mentioned will not work as expected but the value will be updated correctly. That is The console.log will be execute before the setValue because of js async behaviour but at the end of OnChangeHandler, the value will be updated as expected. As @AdriSolid mentioned the best way to look at the value updated is by using the useEffect hook and it is not remended to use console.log to view state values as the behaviour will not be as expected because of async behaviour. It is not that the value is a state behind, The value will be updated correctly its just the execution behaviour which makes us think it is a state behind!

Moreover, you can you useRef hook instead of the event object to update the value

Something like this,

  const ref = useRef();
  const [value, setValue] = useState("");

  useEffect(() => console.log(value), [value]);

  const OnChangeHandler = () => {

    var newValA = ref.current.value
    setValue(newValA)
    // console.log(value)

    return( null )
  }
  return (
    <div className="App">
      <input
        ref={ref}
        value={value}
        onChange={ OnChangeHandler }
      />
    </div>
  );
function A(props){
  const [input, setinput] = useState(props.valA);
  <Input 
    value={input}
    onChange={(e) => setinput(e.target.value)} 
  />
  console.log(input);
}
发布评论

评论列表(0)

  1. 暂无评论