1. // 声明对象类型状态
    2. import { useState } from "react";
    3. function App() {
    4. const [count, setCount] = useState({
    5. count1: 0,
    6. count2: 0,
    7. });
    8. return (
    9. <div className="App">
    10. <button
    11. type="button"
    12. onClick={() =>
    13. setCount((x) => {
    14. return {
    15. ...x,
    16. count1: x.count1 + 1,
    17. };
    18. })
    19. }
    20. >
    21. count is: {count.count1}
    22. count is: {count.count2}
    23. </button>
    24. </div>
    25. );
    26. }
    27. export default App;
    28. // 多次声明
    29. const [count1, setCount1] = useState(0)
    30. const [count2, setCount2] = useState(0)

    可以发现,相比于对象类型状态 ,多次声明状态的方式更加方便,主要是因为更新函数采用的是替换的方式而不是合并。
    不过如果要在函数组件中处理多层数据嵌套逻辑,使用useState就显得力不从心了。好在开发者可以使用useReducer来处理此类问题:

    import { useReducer } from "react";
    
    function App() {
      function reducer(state, action) {
        switch (action.type) {
          case "increment1":
            return { ...state, count1: state.count1 + 1 };
          case "increment2":
            return { ...state, count2: state.count2 + 1 };
          default:
            throw new Error();
        }
      }
      const [state, dispatch] = useReducer(reducer, {
        count1: 0,
        count2: 0,
      });
      return (
        <>
          <button onClick={() => dispatch({ type: "increment1" })}>
            count1: {state.count1}
          </button>
          <button onClick={() => dispatch({ type: "increment2" })}>
            count2: {state.count2}
          </button>
        </>
      );
    }
    
    export default App;