reactjs - redux 动态地将属性添加到对象
问题描述
嗨,我有一个reducer
包含一个array
。objects
这些objects
有一些属性。当我dispatch
在使用时action
,我想动态添加更多属性。我怎样才能实现这个东西redux
useDispatch 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
},
});
解决方案
我不确定你到底想做什么,但我想你可以在你得到它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
组件时执行类似的操作。
希望这对您有所帮助。
推荐阅读
- c++ - python unicodedata库的C++实现
- html - 将选项文本旋转 180 度
- c# - 使用 C# 调用 LinkedIn API
- ios - iOS - Expo Notifications.getExpoPushTokenAsync() 未获得令牌
- python - 表单字段的 Python Django PDF 展平
- javascript - 如何使用php中的while循环和javascript显示从数据库中获取的多个图像中的特定点击图像?
- mysql - 检查mysql是否有index null
- python - 字典列表中的唯一元素有效
- c# - 将架构添加到 Avro 片段 .Net
- asp.net - 有条件地使用 ADFS 登录