反应useState和setState行为错误

我一直在测试状态的变化,以便能够依赖它们并计算其他状态,但是根据实现的不同,我会得到多个结果,尤其是其中一个我不知道或不知道发生了什么或为什么会发生给出结果,请注意console.log()

情况1

const [state, setState] = useState({count: 0});

const handleCount = () => {
    console.log(state); // prints {count: 0}
    setState(prevState => {
      prevState.count = prevState.count + 1;
      return prevState;
    });
    console.log(state); // prints {count: 1}
  }

useEffect(() => {
    console.log('has changed.. ' + state.count)
  }, [state]); // in this case this doesn't show any changes, so isn't renders anything, I need to render this value

// in render
<Button onClick={() => handleCount()}>
   Click {state.count}
</Button>

案例:2

const handleCount = () => {
    console.log(state); // prints {count: 0}
    setStateV(prevState => ({...prevState, count: prevState.count + 1}));
    console.log(state); // prints {count: 0}
  }

useEffect(() => {
    console.log('has changed.. ' + state.count)
  }, [state]); // it show that changed, but I cant depend on this because it haven't changed when I needed it

案例:3

const [state, setState] = useState(0);
const handleCount = () => {
  console.log(state); // prints 0
  setState(state => state + 1);
  console.log(state); // prints 0 it supposed to be 1!
}

I have read this but not worked at all

所以,我需要帮助以了解发生了什么...

评论
  • punde
    punde 回复

    实际上,您正在更改给您错误结果的prevState参数,请尝试以下操作:

    setState(prevState => {
      const count = prevState.count + 1
      return { ...prevState, count }
    })