遍历 getter 和 setter 反应状态挂钩

Iterate through getter and setter react state hooks

在使用状态挂钩公开多个状态属性的 React 组件中,有没有一种方法可以遍历所有状态属性并可能更改它们?问题是我有很多状态属性,所以我不想硬编码所有的 getter 和 setter 来迭代状态属性。

在这个例子中,假设我所有的状态属性都有默认值 0,如果它们不同,我想做点什么。我如何遍历状态属性?

const exampleComponent = () => {

  const [prop1, setProp1] = React.useState(0);
  const [prop2, setProp2] = React.useState(0);
  const [prop3, setProp3] = React.useState(0);
  //...etc., lots of properties

  // Loop over the properties. How should this loop be written?
  Object.keys(this.state).map(function (key) {
    // do something with each key-value pair here
  });

如果您需要遍历属性,我会使用状态数组代替:

const [numArr, setNumArr] = useState([0, 0, 0]);
// ...
numArr.forEach((num, i) => {
  // do something with each key-value pair here
});

如果您有很多彼此相关的状态,那么最好不要使用 useReducer 挂钩,而不是单独处理每个状态。

编辑: 抱歉,我应该早点提到,使用 useReducer 钩子处理状态可能有点冗长,如果不熟悉它可能会很复杂。

这是一个例子,我们有一个具有三个属性的状态对象,而不是三个独立的状态,当 UPDATE_ACTION1 被分派时,代码循环遍历属性并且所有相关的属性都递增2.

//define some actions 
const UPDATE_ACTION1 = "UPDATE_ACTION1";
const UPDATE_ACTION2 = "UPDATE_ACTION2";

//define a reducer function that will update the state
const objReducer = (state, action) => {
  switch (action.type) {
    case UPDATE_ACTION1:
      const keys = Object.keys(state);
      const newState = {};
      keys.forEach(key => {
        //perform any function on each property/key
        //here we just increment the value of each property by the given value
        if (key !== "isValid") {
          newState[key] = state[key] + action.value;
        }
      });
      return newState;

    case UPDATE_ACTION2:
      //do something else e.g. check validity and return updated state
      return { ...state, isValid: true };
    default:
      return state;
  }
};


//inside the component: call useReducer and pass it the reducer function and an initial state
//it will return the current state and a dispatch function
const [objState, dispatch] = useReducer(objReducer, {
   prop1: 0,
   prop2: 0,
   prop3: 0
});

//somewhere in your code, dispatch the action. it will update the state depending upon the action.  
const somethingHappens = () => {
   //some other operations are performed here
   dispatch({ type: UPDATE_ACTION1, value: 2 });
};

另一种方法是将您想要的状态分配到数组中,然后将它们解构为命名常量(如果需要)并枚举 states 数组。请参阅下面的示例:

const exampleComponent = () => {
  const states = [React.useState(0), React.useState(0), React.useState(0)];
  const [
    [prop1, setProp1],
    [prop2, setProp2],
    [prop3, setProp3],
  ] = states;

  // Loop over the properties.
  states.forEach(([state, setState]) => {
    // do something with each key-value pair here
  });
}