如何在React状态中的另一个复杂对象中整齐地推动对象?
我正在尝试使用React Hook在
const [strategy, setStrategy] = useState([leg]);
位置
const leg = {
entry: {
conditions: [],
actions: [""],
},
exit: {
conditions: [],
actions: [""],
},
};
和
const condition = (param) => {
return { param, val: "" };
};
现在声明复杂的数组,以下代码在数组中添加腿部
const addLeg = () => {
const temp_strategy = [...strategy];
temp_strategy.push(leg);
setStrategy(temp_strategy);
};
现在正常工作,我想在给出索引的一个腿中添加条件(在按钮上单击前端),以下是我
const addCondition = (index, trigger, condition_param) => {
// index is for leg
// trigger is either 'entry' or 'exit'
const temp_strategy = [...strategy];
temp_strategy[index][trigger]['conditions'].push(condition(condition_param));
setStrategy(temp_strategy);
};
现在尝试的代码,如果在某个时候策略有3腿,如果我打电话
addCondition(1, 'entry', 'and')
,则将上述条件附加到所有3条腿上,而在“入口”对象内。
我的疑问是为什么它不适用于索引,而是为触发索引和触发器所做的触发器工作
temp_strategy[index][trigger]['conditions'].push(condition(condition_param));
I am trying to declare a complex array using react hook as
const [strategy, setStrategy] = useState([leg]);
where
const leg = {
entry: {
conditions: [],
actions: [""],
},
exit: {
conditions: [],
actions: [""],
},
};
and
const condition = (param) => {
return { param, val: "" };
};
Now, the following code to add a leg in the array is working fine
const addLeg = () => {
const temp_strategy = [...strategy];
temp_strategy.push(leg);
setStrategy(temp_strategy);
};
Now, I want to add a condition in one of the legs whose index is given (on a button click in the front-end), following is the code I am trying
const addCondition = (index, trigger, condition_param) => {
// index is for leg
// trigger is either 'entry' or 'exit'
const temp_strategy = [...strategy];
temp_strategy[index][trigger]['conditions'].push(condition(condition_param));
setStrategy(temp_strategy);
};
Now if at some point strategy is having 3 legs and if I call
addCondition(1, 'entry', 'and')
then it is appending the above condition to all 3 legs but inside the 'entry' object.
My doubt is why it is not working for the index but it is working for the trigger where index and trigger are as
temp_strategy[index][trigger]['conditions'].push(condition(condition_param));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个专门为这种场景
insmer.js
建造的美丽库。请在There is a beautiful library specially built for such a scenario
immer.js
. Go check this out at https://www.npmjs.com/package/immer