Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 未在React.js中设置的上下文更新_Reactjs_Use Context - Fatal编程技术网

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

Reactjs 未在React.js中设置的上下文更新,reactjs,use-context,Reactjs,Use Context,我试图将一个值设置为context/state的值,但它正在更新contaxt/state的值。正如您在下面看到的,我将newParticipants设置为等于global.participants的数组,然后当我单击按钮时,它获取该按钮的值并将其推送到newParticipants数组。出于某种原因,它正在更新global.paricipants,就像我在调用setGlobal一样。我错过了什么?我不想更新上下文 const { global, setGlobal } = useContext

我试图将一个值设置为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);
    ... 
};

啊,谢谢!!我把我的数组当作一个变量!谢谢你的帮助!很高兴能帮忙。