I use the following pattern fairly often while using React:
const {foo, bar, pem, das} = this.props;
const props = {foo, bar, pem, das};
return (
<MyComponent {...props}/>
);
I'm just curious if there are any syntactical shortcuts that have escaped me to cut out a step here. Thanks.
See Destructuring Assignment
, Array.prototype.reduce()
, and Closures
for more info.
// Input. const input = { props: {A: 1, B: 2, C: 3, D: 4, E: 5} } // Select specific keys. const props1 = (({ A, C, D }) => ({ A, C, D }))(input.props) console.log('Select 1', props1) // Functional Select. const select = (obj, ...keys) => keys.reduce((x, k) => ({...x, [k]: obj[k]}), {}) console.log('Select 2', select(input.props, 'A', 'C', 'D')) // Exclude specific keys. const { A, C, D, ...props2 } = input.props console.log('Exclude', props2)
Write a function to select the appropriate properties and add them to an object:
function reduceObjectToTheseProps(obj, props) {
return props.reduce((filteredObjSoFar, prop) => {
filteredObjSoFar[prop] = obj[prop];
return filteredObjSoFar;
}, {});
}
const reducedObj = reduceObjectToTheseProps(myObject, ['foo', 'bar']);
There is really no need for the temporary variables. Why not destructure in the render params?
render = ({ foo, bar, pem, das }) => <MyComponent {...{ foo, bar, pem, das }} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.