setState doesn't update the state immediately

前端 未结 12 2537
暖寄归人
暖寄归人 2020-11-21 05:25

I would like to ask why my state is not changing when I do an onclick event. I\'ve search a while ago that I need to bind the onclick function in constructor but still the s

12条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 06:01

    For anyone trying to do this with hooks, you need useEffect.

    function App() {
      const [x, setX] = useState(5)
      const [y, setY] = useState(15) 
    
      console.log("Element is rendered:", x, y)
    
      // setting y does not trigger the effect
      // the second argument is an array of dependencies
      useEffect(() => console.log("re-render because x changed:", x), [x])
    
      function handleXClick() {
        console.log("x before setting:", x)
        setX(10)
        console.log("x in *line* after setting:", x)
      }
    
      return <>
        
    x is {x}.
    y is {y}.
    }

    Output:

    Element is rendered: 5 15
    re-render because x changed: 5
    (press x button)
    x before setting: 5
    x in *line* after setting: 5
    Element is rendered: 10 15
    re-render because x changed: 10
    (press y button)
    Element is rendered: 10 20
    

提交回复
热议问题