简体   繁体   English

反应const改变值?

[英]React const changing value?

How is it possible, I'm creating a const to get the old messages from my chat, so I can know if has a new message comming from the database or something like that, but there is something wierd with my code, the const is changing value 我怎么可能创建一个const来从聊天中获取旧消息,所以我可以知道数据库中是否有新消息或类似的消息,但是我的代码有些奇怪,const是改变价值

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, …}

You can see, I don't even call the variables, except in the consoles 您可以看到,除了控制台之外,我什至没有调用变量

Has something to do with the reference? 与参考有关吗?

PS: messages is a reference of this.state.messages too PS: messages也是this.state.messages的引用

const doesn't do what you think it does. const不会执行您认为的操作。

const prevents re-assigment of a variable: const防止重新赋值变量:

const arr = []; 

arr.push(1); // works

console.log(arr); // [1]

arr = []; // whoops

One thing to know about const is that 关于const一件事是

Constants are block-scoped, much like variables defined using the let statement. 常量是块作用域的,非常类似于使用let语句定义的变量。 The value of a constant cannot change through re-assignment, and it can't be redeclared. 常量的值不能通过重新分配而更改,也不能重新声明。

In your case you are not reassigning the const variable, but mutating its original value which is possible 在您的情况下,您不是要重新分配const变量,而是要更改其原始值(可能的话)

What you are looking for is an Immutable data which doesn't change it value but creates a new reference of the original data and updates it. 您正在寻找的是Immutable数据,它不会更改其值,而是会为原始数据创建一个新引用并进行更新。 Look into libraries such as Immutable-JS 研究诸如Immutable-JS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM