如何解决遍历getter和setter react状态挂钩
在使用状态钩子暴露几个状态属性的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
});
解决方法
另一种方法是将所需的状态分配到数组中,然后将其分解为命名常量(如果需要),并枚举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
});
}
,
如果您需要遍历属性,我将使用状态数组:
const [numArr,setNumArr] = useState([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 });
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。