首页 > 解决方案 > redux 动态地将属性添加到对象

问题描述

嗨,我有一个reducer包含一个arrayobjects这些objects有一些属性。当我dispatch在使用时action,我想动态添加更多属性。我怎样才能实现这个东西reduxuseDispatch Hook

//减速机数据

    users: [
    {
      id: 1,
      first_name: "JACKILINE",
      status: "online",
    },
    {
      id: 2,
      first_name: "BRONNNZE",
      status: "offline",
      
     },
  ];

我想动态添加这两个属性mesg: "how are you",lastSeenDate: "30/11/19", 如何更新减速器中的状态

//我希望在调度一个动作后像这样的减速器

users: [
    {
      id: 1,
      first_name: "JACKILINE",
      status: "online",
      mesg: "how are you",
      lastSeenDate: "30/11/19",
      
    },
    {
      id: 2,
      first_name: "BRONNNZE",
      status: "offline",
      mesg: "how are you",
      lastSeenDate: "30/11/19",
     
    },
  ],
      `

//我的动作

export const setLastMessage = (payload) => ({
  type: actionTypes.SET_LAST_MESSAGE,
  payload: {
    id: payload.id,
    lastSeenDate: payload.date,
    mesg:payload.message
    
  },
});

标签: reactjsreduxreact-reduxreact-hooks

解决方案


我不确定你到底想做什么,但我想你可以在你得到它users而不是在你导入它的时候做。

你怎么得到users

请尝试在您的切片文件中执行此操作(可能是 src/slices/user.js)。

const initialState = {
  users: []
}
const slice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    getUsers(state, action) {
      const { users } = action.payload;

      state.users = users.map(user => ({
        ...user,
        mesg: "how are you",
        lastSeenDate: "30/11/19"
      }))
    },
  }
});

export const reducer = slice.reducer;

export const getUsers = () => async (dispatch) => {
  const response = await axios.get('/api/users');

  dispatch(slice.actions.getUsers(response.data));
};

或者您可以在导入users组件时执行类似的操作。

希望这对您有所帮助。


推荐阅读