An example of destructuring
When I saw this kind of shape below on parameter of function for the first time, it was hard to guess what it means. It meant to cut down a length of code from ‘props.song’ to ‘song’ by not using ‘props’.
function foo({song}) {
...
}
Before :
import React from 'react';import { connect } from 'react-redux';
const SongDetail = props => { if (!props.song) { return <div>Select a song!</div> } return <div>{props.song.title}</div>;};
const mapStateToProps = (state) => { return { song: state.selectedSong}};
export default connect(mapStateToProps)(SongDetail);
After :
import React from 'react';import { connect } from 'react-redux';
const SongDetail = ({song}) => { if (!song) { return <div>Select a song!</div> } return <div>{song.title}</div>;};
const mapStateToProps = (state) => {return { song: state.selectedSong}};
export default connect(mapStateToProps)(SongDetail);
Reference :
- https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
I am blogging what I’ve learned to find later here for myself. If you happened to read this shit and there is wrong information, it would be appreciated to add a comment below.