如何减少 React JS 中的状态

How to reduce states in react JS

我有一个组件需要处理多个状态,这就是我声明多个状态的原因。有没有办法优化 hooks 组件中的状态

const [showPopup, setShowPopup] = useState(false);
  const [camPopup, setCamPopup] = useState(false);
  const [color, setColor] = useState("red");
 const [userdata, setUserdata] = useState(null);

还有几个州是如何优化/减少它们的。

您可以使用 useState 将它们放入一个对象中:

const [state, setState] = useState({
    showPopup: false,
    camPopup: false,
    color: "red",
    userdata: null,
});

// Destructure state, so we don't have to write state.something everytime
const {showPopup, camPopup, color, userdata} = state; 

但是注意,在复杂的状态下,我们也可以使用useReducer:

const initialState = {
    showPopup: false,
    camPopup: false,
    color: "red",
    userdata: null,
}

const [state, dispatch] = useReducer(reducer, initialState);

const {showPopup, camPopup, color, userdata} = state; // Destructure

function reducer(state, action) {
  switch (action.type) {
    case 'login':
      // we can't mutate state directly, but will have to return a new state object
      return {...state, userData: action.payload}; 
    default:
      throw new Error();
  }
}