在使用状态挂钩公开多个状态属性的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
  });发布于 2020-10-17 00:40:21
另一种方法是将想要的状态分配到数组中,然后将它们分解为指定的常量(如果需要的话),并枚举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
  });
}
发布于 2020-10-16 23:39:47
如果您需要循环这些属性,我将使用一个数组作为状态:
const [numArr, setNumArr] = useState([0, 0, 0]);
// ...
numArr.forEach((num, i) => {
  // do something with each key-value pair here
});发布于 2020-10-17 00:21:58
如果您有许多相互关联的状态,那么与其将每个状态分开,不如使用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 });
};https://stackoverflow.com/questions/64397707
复制相似问题