gpt4 book ai didi

javascript - 将键值对添加到 redux store

转载 作者:行者123 更新时间:2023-11-30 20:06:41 25 4
gpt4 key购买 nike

我正在尝试使用 redux 将键值对添加到我的商店。但是,我不确定如何完成此操作。简而言之,我正在从 firebase 检索数据,我想将该数据添加到我的 redux 存储中,但我必须一次做一个项目。我想要的状态对象结构是这样的:

reminders
- reminder key 1
- reminder title
- reminder date 1
- reminder key 2
- reminder title
- reminder date 1

等等。

但我不知道如何将 child 添加到我的 state.reminders 对象

这是我的操作:

const fetchReminders = (uid) => async dispatch => {
firebaseReminders.child(uid).orderByChild("date").on("value", snapshot => {

snapshot.forEach(function(child) {
console.log(child.val())
dispatch({
type: 'fetchReminders',
value: child.val(),
key: child.key
});
})

});
};

所以这将为我从数据库中检索到的每个项目分派(dispatch)操作,然后在我的 reducer 中,我想使用 action.key 作为键将该项目添加到状态树中。目前我有

const remindersReducer = (state = initialState, action) => {

switch(action.type) {

case "fetchReminders":
return Object.assign({}, state, {
reminders: action.value
});


default: return state;
}

};

这是不正确的。如何使用 action.key 的键和 action.value 的值将子节点添加到我的 state.reminders 对象

最佳答案

let initialState = {
reminders: {}
}

const remindersReducer = (state = initialState, action) => {
switch(action.type) {
case "fetchReminders":
return Object.assign({}, state, {
reminders: {
...state.reminders,
[action.key]: action.value
}
});
default: return state;
}
};

let state1 = remindersReducer(initialState, {
type: 'fetchReminders',
key: 'reminderKey1',
value: 'reminderValue1'
});
console.log(state1)

let state2 = remindersReducer(state1, {
type: 'fetchReminders',
key: 'reminderKey2',
value: 'reminderValue2'
});
console.log(state2)

let state3 = remindersReducer(state2, {
type: 'fetchReminders',
key: 'reminderKey3',
value: 'reminderValue3'
});
console.log(state3)

该片段应该可以帮助您实现您想要做的事情。您可以使用以下格式将对象指定为 action.key 的键:

{
[action.key]: action.value
}

它称为计算属性名称。

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. Source

关于javascript - 将键值对添加到 redux store,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52847072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com