簡體   English   中英

ES6在構造函數之外的解構分配

[英]ES6 destructuring assignment outside of constructor

我正在開發一個基於react的項目,並且正在使用ES6和babel Transpile工具和插件。 我知道在類的構造函數中解構分配,如下所示:

~~~
constructor(props){
  super(props);

  ({
    name: this.name,
    family: this.family
  } = props);
}
~~~

上面的代碼代替this.name = props.name; 並且this.family = props.family;

但我不使用構造函數,因為我用babel-plugin-transform-class-properties ,我並不需要有constructorthis.state並結合this對每一個類的功能。 我只聲明state並將函數聲明為箭頭函數,請參見以下示例:

class Sample extends React.PureComponent {
  state = {
    ~~~
  };

  handleSample = () => { ~~~ };

  ~~~
}

但是現在我不知道如何在類主體內部的構造this.props之外解構this.props並將其添加到this 我測試了一些嘗試,但是它們有語法錯誤:

({
  name: this.name,
  family: this.family
} = this.props);

我怎么寫呢?

您必須單獨列出所有內容:(如果要在課堂上使用)

name = this.props.name
family = this.props.family

但這對我來說似乎不必要,您可能想在該狀態下使用:

state = {
  name: this.props.name
  family: this.props.family
}

但是,如果您需要在其他地方使用,可以執行以下操作:

render() {
  const { name, family } = this.props

編輯:

1.您可以使用構造函數並將道具傳遞給狀態。 如果使用箭頭函數,則不必為每個函數都進行綁定(盡管創建函數和綁定的編譯速度比箭頭函數要快)。

2.您可以在州內使用道具並執行以下操作:

state={prop1: this.props.prop1,prop2: this.props.prop2,...}

然后使用狀態代替

3.另一種解決方案是使用鈎子 ,這是一個新功能,使您能夠在功能組件中使用狀態,並通過將props作為參數傳遞給函數聲明來使用props。 因此,您的組件將變為:

class Example extends React.Component {
  state = {
   .....
  }
  .
  .
  .
  render() {
    const {prop1, prop2, ...}=this.props
    return {......};
  }
}

對此:

 function Example(props) {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
  const {prop1, prop2, ...} = props;
  .
  .
  .
  return (
    ....
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM