如何在React状态中的另一个复杂对象中整齐地推动对象?

发布于 2025-02-01 22:37:44 字数 1186 浏览 4 评论 0原文

我正在尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七婞 2025-02-08 22:37:46

有一个专门为这种场景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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文