不在React.js中设置上下文更新



我试图将值设置为context/state的值,但它正在更新contaxt/state的值。如下所示,我将newParticipants设置为global.participants数组,然后当我单击按钮时,它会获取该按钮的值,并将其推到newParticipients数组中。出于某种原因,它正在更新global.paricitions,就好像我在调用setGlobal一样。我错过了什么?我不想更新上下文。

const { global, setGlobal } = useContext(GlobalContext);
let newParticipants = global.participants;
const click = (event) => {
newParticipants.push(event.currentTarget.attributes[1].value);
axios.put(
"http://localhost:8080/update/participants",
{ old: global.participants, new: newParticipants },
{
headers: { authorization: "Bearer: " + localStorage.getItem("Auth") },
}
);
};

在将原始数组分配给newParticipants后,当您引用同一个数组时,您正在更改原始数组,您应该在更新参与者列表之前克隆该列表

const { global, setGlobal } = useContext(GlobalContext);
// shallow clone the list
let newParticipants = [...global.participants];
const click = (event) => {
newParticipants.push(event.currentTarget.attributes[1].value);
... 
};

最新更新