Reactjs:将 props 分配给 const 变量有什么好处?

ins*_*ral 2 reactjs

我在很多例子中看到了以下实践,即使只有一个道具:

render() {
  const { thisProp, thatProp } = this.props;

  return (
    <Component passedPropA={thisProp} passedPropB={thatProp} />
  );
}
Run Code Online (Sandbox Code Playgroud)

创建相同数据的另一个副本有什么好处?为什么不直接使用这样的道具呢?

render() {

  return (
    <Component passedPropA={this.props.thisProp} passedPropB={this.props.thatProp} />
  );
}
Run Code Online (Sandbox Code Playgroud)

J L*_*ood 5

我认为这个问题确实达到了 2 分。一种是将 const 用于不可变变量,另一种是解构。

为了回答这个问题,使用 const 是因为它是不可变的,你不应该直接修改传递给你的东西。

但是您在维护良好的代码库中看到这一点的原因是为了可读性。您可以准确地看到传递的内容和第一行中使用的内容,以及在没有调用整个路径的情况下使用它的地方更加清晰简洁this.props.thisProp。这里没有显示的是它的一些真正的力量,例如默认值和别名,尽管这有助于保持代码的可读性。喜欢:

const { thisProps : thisParentsProp = 'empty' } = this.props;
Run Code Online (Sandbox Code Playgroud)