关于 javascript 如何使用包含键的方括号作为 属性 访问器来更新对象条目的问题

Question about how javascript is able to update an object entry using square brackets containing a key as the property accessor

基于 youtube 上的教程 (https://www.youtube.com/watch?v=hiiaHyhhwBU&t=1195s) 我正在编写一个聊天应用程序,使用反应挂钩,特别是 useReducer()。但我不明白在 switch 情况下如何返回状态的更新版本只保留两个元素并且不向 initState 添加第三个元素:

const initState = {
    general: [
        {from: 'ciro', msg: 'bella'},
        {from: 'ciro', msg: 'bella'},
        {from: 'ciro', msg: 'bella'}
    ],
    private: [
        {from: 'gennaro', msg: 'hello'},
        {from: 'gennaro', msg: 'hello'},
        {from: 'gennaro', msg: 'hello'}
    ]
}

const reducer = (state, action) => {
    const { topic, from, msg } = action.payload;

    switch(action.type) {
        case 'RECEIVE_MESSAGE':
            return {
                ...state,
                [topic]: [
                    ...state[topic],
                    {
                        from: from,
                        msg: msg
                    }
                ]
            }
        default:
            return state;
    }
} 

我想知道 [topic] 是如何更新与该主题对应的消息列表的,因为它没有直接链接到 ...state?以及如何...状态不只是添加第三个元素?我觉得这很混乱。

            return {
                ...state,
                [topic]: [
                    ...state[topic],
                    {
                        from: from,
                        msg: msg
                    }
                ]
            }

感谢您的帮助

你可以参考这个文档:

基本上当你问:

how to the ...state is not just added a third element?

因为:

The Rest/Spread Properties for ECMAScript proposal (ES2018) added spread properties to object literals. It copies own enumerable properties from a provided object onto a new object. Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

如果对象有同名的 属性,则最右边的对象 属性 会覆盖前一个。

关于:

I wonder how is [topic] able to update the message list corresponding to the topic?

我觉得这个:说的很清楚,如果不是请尽管问。