Langsung saja kita mulai:
Misal kita mempunyai object yang memiliki lebih dari 10 atribut seperti ini:
var state = {
     name:"Andy wiranta wijaya",
     address:"Jl. xxx", 
     phoneNumber:"+627272727227",
     sex:"pria",
     ....
Nah, saya hanya butuh  2 atribut name dan address yang akan saya tampung di suatu variabel.
//Cara konvensional 
var name = state.name;
var address = state.address;
//Object destructuring
const { name, address } = state;
Simple, clean,  pretty dan readable. Coba kalian bayangkan jika kalian passing lebih dari 10 atribut. Contoh ke dua:
var state = {
 name : "budi",
 address:"Jl kebon timur no 7-8",
 sex : "pria",
 hobby:"main bola"
}
printMyNameAndAddress(state)
function printMyNameAndAddress({name, address}){
 console.log(`my name is ${name} and address ${address}`);
}
Hasilnya:Mari kita implementasikan di react component, sebelum (destructuring):
render() {
  return (
    <ProductPrice
      hidePriceFulfillmentDisplay=
       {this.props.hidePriceFulfillmentDisplay}
      primaryOffer={this.props.primaryOffer}
      productType={this.props.productType}
      productPageUrl={this.props.productPageUrl}
      inventory={this.props.inventory}
      submapType={this.props.submapType}
      ppu={this.props.ppu}
      isLoggedIn={this.props.isLoggedIn}
      gridView={this.props.isGridView}
    />
  );
}
Bisa dilihat sendiri banyak penggunaan this.props :o, mari kita perbaikin dengan seperti ini:
render() {
  const {
    hidePriceFulfillmentDisplay,
    primaryOffer,
    productType,
    productPageUrl,
    inventory,
    submapType,
    ppu,
    isLoggedIn,
    gridView
  } = this.props;
return (
    <ProductPrice
      hidePriceFulfillmentDisplay={hidePriceFulfillmentDisplay}
      primaryOffer={primaryOffer}
      productType={productType}
      productPageUrl={productPageUrl}
      inventory={inventory}
      submapType={submapType}
      ppu={ppu}
      isLoggedIn={isLoggedIn}
      gridView={isGridView}
    />
  );
}
Kesimpulan:
Remember, beautiful code does a lot without saying much.Sumber:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
Inspirasi quote:
https://medium.com/walmartlabs/make-your-react-components-pretty-a1ae4ec0f56e#.qlgf8l272
already implemented it :)
ReplyDeletecheck my github/post :D http://blog.nostratech.com/2016/12/membuat-generic-dropdown-dengan-reactjs.html
cool :)
DeleteThis comment has been removed by the author.
ReplyDelete