在 Firebase 'child_removed' 侦听器触发后从 redux 状态中移除嵌套子级

Remove nested child from redux state following Firebase 'child_removed' listener triggered

我的 redux 状态看起来像这样(它与 Firebase 同步)。

{
  profile: {
    activeUsers: {
      Iiva2BGZffNTH84glOLXv8QHVTF2: {
        sex: male,
        age: 20,
      },
      PkfMxrN09RN7ygoBMWqm4jheEOx1: {
        sex: female,
        age: 20,
      },
      zQiGXvcUGmRSKUdr719621QleUw2: {
        sex: male,
        age: 25,
      }
    }
  }
}

我想删除用户 zQiGXvcUGmRSKUdr719621QleUw2

这是我的动作创作者

  Firebase.database()
    .ref('profiles/activeUsers')
    .on(
      'child_removed',
      (snapshot) => {
        dispatch(_activeUserChildRemoved(snapshot));
      },
      (err) => {
        console.log(err.toString());
        Alert.alert(err);
      },
    );
};

const _activeUserChildRemoved = snapshot => ({
  type: ACTIVE_USER_CHILD_REMOVED,
  payload: snapshot,
});

最后是我的减速器

  switch (action.type) {
    case ACTIVE_USER_CHILD_REMOVED:
      const key4Del = action.payload.key;
      return { //what goes here??? };
    default:
      return state;
  }
};

为了从 redux 中删除 snapshot.key 引用的用户,我从 reducer return 做什么? 非常感谢帮助

知道了!!

case ACTIVE_USER_CHILD_REMOVED:
      const key4Del = action.payload.key;
      const oldState = state;
      delete oldState.activeUsers[key4Del];
      return { ...oldState };

您需要通过不改变 状态并简单地使用解构.

来删除用户

现在您正在通过从 oldState

中删除对象 属性 来直接改变 state
case ACTIVE_USER_CHILD_REMOVED:
  const key4Del = action.payload.key;
  const { [key4Del]: _, ...activeUsers} = state.activeUsers
  return {...state, activeUsers }

Spread Syntax 会对对象进行浅比较,因此您需要再次合并过滤后的对象以生成新的状态。