reactjs 更新对象redux数组中的特定对象值

ws51t4hk  于 2023-01-04  发布在  React
关注(0)|答案(1)|浏览(141)

我的目标是更新chatId#1(或chats数组中的第一个对象)的animatedPhotoUrl值。

const chats = [

  {"admin": "590", 
  "animatedPhotoUrl": "", 
  "chatId": "1"}, 

  {"admin": "680", 
   "animatedPhotoUrl": "", 
   "chatId": "2"},
  {"admin": "420", 
   "animatedPhotoUrl": "", 
   "chatId": "2"}

]

然而,当我在reducer中更新后,我得到了错误:
[undefined, undefined]
以下是我的急件:

dispatch({
          type: "UPDATE_CHAT_PROFILE_PICTURE_URL",
          payload: {
            profilePictureUrl: res.imageUrl,
            animatedPhotoUrl: "",
            chatId: chat.chatId,
          },
        });

这是我的减速器里的代码

case "UPDATE_CHAT_PROFILE_PICTURE_URL":
      return {
        ...state,
        chats: state.chats.map((chat) => {
          chat.chatId === action.payload.chatId
            ? {
                ...chat,
                animatedPhotoUrl: action.payload.animatedPhotoUrl,
              }
            : chat;
        }),
      };
zrfyljdw

zrfyljdw1#

您需要在此处添加return

chats: state.chats.map((chat) => {
  return chat.chatId === action.payload.chatId
    ? {
        ...chat,
        animatedPhotoUrl: action.payload.animatedPhotoUrl,
      }
    : chat;
}),

或者你需要去掉大括号来得到隐式的return

chats: state.chats.map((chat) => 
  chat.chatId === action.payload.chatId
    ? {
        ...chat,
        animatedPhotoUrl: action.payload.animatedPhotoUrl,
      }
    : chat;
),

相关问题