Redux const { var1, var2 } = this.props;

Pul*_*wal 5 javascript ecmascript-6 reactjs react-redux

我是反应 js 的新手。我正在做一个项目,发现这条线

 const { var1, var2 } = this.props;  
Run Code Online (Sandbox Code Playgroud)

这个组件中的道具是

type PropsType = {
  var1: Array<any>,
  a: Array<any>,
  b: boolean,
  c: boolean,
  var2: (string) => void,
  d: () => void,
  e: () => void
};  
Run Code Online (Sandbox Code Playgroud)

我很迷惑。这是什么意思?

And*_*rew 7

const { var1, var2 } = this.props;
// the same as
// const var1 = this.props.var1;
// const var2 = this.props.var2;
Run Code Online (Sandbox Code Playgroud)

你有没有试过阅读文档


小智 5

很好的冗余信息,但对我来说是一个修订。:) 无论如何,这是解构对象分配。这意味着,这是从对象(例如这里的 this.props)获取对象属性值的一种速记方式。因此,当您想从“this.props”中提取名为“var1”和“var2”的属性时,通过编写指令 -

const { var1, var2 } = this.props;
Run Code Online (Sandbox Code Playgroud)

您要求将“this.props”中名为“var1”和“var2”的属性存储在常量“var1”和“var2”中。所有其他属性都被简单地忽略。如果任何被询问的属性名称不存在,它们只会被赋予“未分配”值。

在此之后,您可以考虑在这里查看更多细节(它的魔力!) - MDN - object_destructuring