React const changing value?
怎么可能呢,我正在创建一个常量来从我的聊天中获取旧消息,这样我就可以知道是否有来自数据库的新消息或类似的消息,但是我的代码中有一些内容,常量正在改变值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | const oldMessages = this.state.messages.slice(); // Console console.log(oldMessages[oldMessages.length - 1]); // Prints {name:"André", message:"asds", who:"Y", sending: true, local_key: 232, …} newMessages.map((message, key) => { // Here I don't even call the const if (message.local_key != undefined) { const i = messages.map((i) => { return i.local_key }).indexOf(message.local_key); if (i >= 0) { // messages.splice(i, 1); messages[i].id = message.id; messages[i].sending = false; messages[i].local_key = null; newMessages.splice(key, 1); // // Limpar chave do banco // } else { newMessages[key].local_key = null; } } if (newMessages[key] != undefined) { newMessages[key].animate = true; } }); // Console console.log(oldMessages[oldMessages.length - 1]); // Prints {name:"André", message:"asds", who:"Y", sending: false, local_key: null, …} |
你可以看到,除了控制台之外,我甚至不调用变量
与参考有关吗?
附:
关于
Constants are block-scoped, much like variables defined using the let
statement. The value of a constant cannot change through
re-assignment, and it can't be redeclared.
在您的例子中,您不是在重新分配const变量,而是在可能的情况下改变其原始值。
您要查找的是一个
1 2 3 4 5 6 7 | const arr = []; arr.push(1); // works console.log(arr); // [1] arr = []; // whoops |