【问题标题】:Find, update an element and change its index in array of objects查找、更新元素并更改其在对象数组中的索引
【发布时间】:2021-01-31 13:02:26
【问题描述】:

我在这里尝试实现的是聊天应用程序,其中最后一次对话(当前登录用户和目标用户之间)应该更新其 lastMessage 并放置在对话数组中的第一个位置。

这里是对话数组的一个更简单的版本:

const conversations = [
    { ... },
    {
        _id: 5,
        lastMessage: {
            sender: 1
            receiver: 2
            message: 'Hello World',
            conversation_id: 5
        }
    },
    { ... }
]

如果id = 1 的用户向id = 2 的用户发送消息,它应该更新_id = 5 的对话并将其移动到对话数组的索引0。

我目前所做的是将对话移动到数组的顶部,但我不知道如何更改它的 lastMessage。 (反应减速器)

conversations: [state.conversations.find(el => el._id === action.payload.conversation_id), ...state.conversations.filter(el => el._id !== action.payload.conversation_id)]

感谢任何可以帮助我的人!

【问题讨论】:

    标签: arrays reactjs higher-order-functions reducers


    【解决方案1】:

    这样的东西能满足您的要求吗?

    // find the first convo as you already do
    const firstConversation = state.conversations
              .find(el => el._id === action.payload.conversation_id);
    
    // this is the current `lastMessage`
    const lastMessage = {...first.lastMessage};
    
    // make changes to `lastMessage` here, or assign a completely new object as required
    const firstConversationUpdated = {...firstConversation, lastMessage: lastMessage};
    
    // update state below
    conversations: [firstConversationUpdated, 
                    ...state.conversations.filter(el => el._id !== action.payload.conversation_id)]
    

    【讨论】:

    • 我的错,给你
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多