首页 > 解决方案 > 顽固的 Redux 操作发送空数组

问题描述

我有这段代码:

        const result = Object.keys(state).reduce((result, key) => {
        if (key.includes('game')) {
          result[key] = state[key];
        }
        return result;
      }, []);
      this.props.sendBackResult(result);

最后一行当然会触发 Redux 操作。但这不是发送格式良好的数组,而是只发送空数组。这是什么原因?当我插入日志而不是发送操作时,我看到了前一个函数的正确结果。

谢谢!

标签: javascriptreactjsredux

解决方案


您正在使用一个空数组[]作为reduce. 在阵列上设置一个键很可能不是您想要做的事情。

您可以改为推送其中包含的所有键game对应于数组的值:

const result = Object.keys(state).reduce((result, key) => {
  if (key.includes('game')) {
    result.push(state[key]);
  }
  return result;
}, []);

如果您仍然希望最终结果中的键,您很可能希望使用一个对象来代替:

const result = Object.keys(state).reduce((result, key) => {
  if (key.includes('game')) {
    result[key] = state[key];
  }
  return result;
}, {});

推荐阅读