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

Context updating without being set in React.js

我正在尝试将一个值设置为 context/state 的值,但它正在更新 contaxt/state 值。正如您在下面看到的,我将 newParticipants 设置为 global.participants 数组,然后当我单击该按钮时,它会获取该按钮的值并将其推送到 newParticipants 数组。出于某种原因,它正在更新 global.paricipants,就好像我在调用 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);
    ... 
};