【问题标题】:How to destructure an object to retrieve the return value from a method?如何解构对象以从方法中检索返回值?
【发布时间】:2017-04-23 17:46:31
【问题描述】:

我正在研究不变性和 redux,我面临的问题并不严重,但如果有解决方案,那就太好了。答案可能很愚蠢,但由于我是 ES 新手,我在想我们如何才能实现它。

下面是我的减速器:

import Immutable from 'immutable';
import { TODOYO } from '../constants/action-types';

const initialState = Immutable.Map({
  message: null,
});

export default function todos(state = initialState, action) {
  switch (action.type) {
    case TODOYO:
      return state.set('message', action.payload);
    default:
      return state;
  }
}

下面是我在一个组件中的 mapStateToProps 函数:

function mapStateToProps(state) {
  const message = state.todos.get('message');

  return {
    message,
  };
}

如何解构state 以检索消息?

我在想这样的事情:

const {
  todos: {
    message: get('message')
  }
} = state;

这是错误的。有没有办法找回消息?

【问题讨论】:

    标签: javascript ecmascript-6 redux immutability destructuring


    【解决方案1】:

    这是不可能的。只能解构数组/对象,不能在解构中执行函数。

    解构赋值语法是一种 JavaScript 表达式,可以将数据从 数组对象 提取到不同的变量中。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

    【讨论】:

    • 这可能是很好的做类似const {length, firstLetters: substring(0, 5)} = string;imo。
    【解决方案2】:

    如果您没有 message 作为您所在州的键之一,您可以使用 default parameters 语法来执行此操作。如果 message 确实作为您的状态的属性存在,则默认值将被覆盖。所以请谨慎使用。

    function mapStateToProps({ todos, message = todos.get('message') }) {
      return {
        message,
      };
    }
    

    您还可以将mapStateToProps 缩短为箭头函数:

    const mapStateToProps = ({ todos, message = todos.get('message') }) => ({
      message
    });
    

    【讨论】:

    • 有趣。谢谢。
    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多