gpt4 book ai didi

javascript - 在reactjs中更新状态索引的问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:44 24 4
gpt4 key购买 nike

this.state = {foo : [{x:20,y:40},{x:55,y:10},{x:8,y:90},{x:0,y:150}]};//state
this.state.foo[2].x = 80;//change state

我需要更新 x 属性中 foo 的索引 2。但是有了 setState。我该怎么做?

最佳答案

您可以执行以下操作,这将避免对第三方库的需求,同时还能在您的状态更新中保持不变性:

// Clone the foo list from state
const foo = this.state.foo.map(item => ({ ...item }));

// Update element in cloned list
foo[2].x = 80;

// Update state with cloned list
this.setState({ foo });

关于javascript - 在reactjs中更新状态索引的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com