What does the '…rest' stand for, in this spread operator example

痴心易碎 提交于 2021-02-05 08:10:36

问题


I'm reading about unknown-prop warnings in react, particularly because I'm using the react-bootstrap package and have stumbled upon them there.

i've read that: 'To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component', on here:

https://gist.github.com/jimfb/d99e0678e9da715ccf6454961ef04d1b

and an example is given for how the spread operator can be used to pull variables off props, and put the remaining props into a variable.

the example code:

function MyDiv(props) {
  const { layout, ...rest } = props
  if (layout === 'horizontal') {
    return <div {...rest} style={getHorizontalStyle()} />
  } else {
    return <div {...rest} style={getVerticalStyle()} />
  }
}

Here is what the PROBLEM is: In the example given, I don't understand what the '...rest' in this code here stands for. I get that the '...' = spread syntax, but where did the word 'rest' come from and what does it stand for?


回答1:


This is object rest operator, it creates an object from all properties that weren't explicitly destructured.

Note: since object rest/spread is still a stage 3 proposal, and requires a babel transform to work.

const obj = { a: 1, b: 2, c: 3};

const { a, ...everythingElse } = obj;

console.log(a);

console.log(everythingElse);

It's equivalent to array rest operator:

const arr = [1, 2, 3];

const [a, ...rest] = arr;

console.log(a);
console.log(rest);



回答2:


Don't confuse rest operator (...) and spread operator (that is also ...):

'...' acts as a rest operator in the code below:

const { layout, ...rest } = props

but in the code below, '...' acts as a spread operator:

return <div {...rest} style={getHorizontalStyle()} />


来源:https://stackoverflow.com/questions/47689680/what-does-the-rest-stand-for-in-this-spread-operator-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!