【问题标题】:Adding key value pairs to redux store将键值对添加到 redux 存储
【发布时间】:2018-10-17 03:58:27
【问题描述】:

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

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

等等。

但我不知道如何将孩子添加到我的 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
        });
      })

    });
};

所以这将为我从数据库中检索到的每个项目分派操作,然后在我的减速器中,我想使用 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 对象添加子节点

【问题讨论】:

    标签: javascript firebase firebase-realtime-database redux


    【解决方案1】:

    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)

    sn-p 应该可以帮助您实现您想做的事情。 您可以使用以下格式将对象分配为 action.key 的键:

    {
      [action.key]: action.value
    }
    

    它称为计算属性名称。

    从 ECMAScript 2015 开始,对象初始值设定项语法也 支持计算属性名称。这允许您放置一个表达式 在括号 [] 中,它将被计算并用作属性名称。 Source

    【讨论】:

      猜你喜欢
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 2019-01-27
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-02-11
      相关资源
      最近更新 更多