Reactjs 未在React.js中设置的上下文更新
我试图将一个值设置为context/state的值,但它正在更新contaxt/state的值。正如您在下面看到的,我将newParticipants设置为等于global.participants的数组,然后当我单击按钮时,它获取该按钮的值并将其推送到newParticipants数组。出于某种原因,它正在更新global.paricipants,就像我在调用setGlobal一样。我错过了什么?我不想更新上下文Reactjs 未在React.js中设置的上下文更新,reactjs,use-context,Reactjs,Use Context,我试图将一个值设置为context/state的值,但它正在更新contaxt/state的值。正如您在下面看到的,我将newParticipants设置为等于global.participants的数组,然后当我单击按钮时,它获取该按钮的值并将其推送到newParticipants数组。出于某种原因,它正在更新global.paricipants,就像我在调用setGlobal一样。我错过了什么?我不想更新上下文 const { global, setGlobal } = useContext
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);
...
};
啊,谢谢!!我把我的数组当作一个变量!谢谢你的帮助!很高兴能帮忙。