Reactjs 通过map函数了解rest和spread参数的用法
我想了解如何正确使用。。。js中的运算符,特别是使用js映射函数 假设我们有以下数据:Reactjs 通过map函数了解rest和spread参数的用法,reactjs,rest,dictionary,spread,Reactjs,Rest,Dictionary,Spread,我想了解如何正确使用。。。js中的运算符,特别是使用js映射函数 假设我们有以下数据: const SHOP_DATA = [ { id: 1, title: 'Hats', routeName: 'hats', items: [ { id: 1, name: 'Brown Brim', imageUrl: 'https://i.ibb.co/ZYW3VTp/bro
const SHOP_DATA = [
{
id: 1,
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25
}]
}
]
现在我想将值作为道具发送到另一个组件:
SHOP_DATA.map(({ id, ...otherProps }) => (
<CollectionPreview key={id} {...otherProps} />
我不理解数据流,为什么我们刚才所做的等同于:
SHOP_DATA.map(({ id, title , items }) => (
<CollectionPreview key={id} title = {title} items = {items} />
SHOP_DATA.map({id,title,items})=>(
为此,您还需要熟悉解构
如果您有一个对象:
const human = { name: 'John', age: 20, sex: 'Male'}
您可以取出对象的道具,如:
const {name, age, sex} = human
现在,name->“约翰,年龄->20岁,性别->男性”
但如果你这样做了
const {name, ...rest} = human
name -> 'John'
rest -> { age: 20, sex: 'Male'}
现在让我们转到您的代码:
SHOP_DATA.map(({ id, ...otherProps })
在这里,您可以通过数组进行映射,并动态分解对象
id -> id
otherProps -> {
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25
}]
}
因此
<CollectionPreview key={id} {...otherProps} />
将变成
<CollectionPreview key={id} title={title} routerName={routeName} items={items} />
希望这是有帮助的
SHOP_DATA.map({id,…otherProps})
在这里,您正在分解每个SHOP\u DATA
的对象属性,并使用对象的rest操作符初始化一个名为otherProps
的对象,其中所有对象属性减去前面指定的属性(在本例中为“id
”):
这里您使用的是JSX扩展操作符,这与对象扩展操作符有点不同,它将对象的所有属性扩展到通过属性名称命名的组件道具,结果:
<CollectionPreview key={id} title="Hats" routeName="hats" items={[{ id: 1, name: "Brown Brim", etc.. }]} />
otherProps = {
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25,
},
],
};
<CollectionPreview key={id} title="Hats" routeName="hats" items={[{ id: 1, name: "Brown Brim", etc.. }]} />
const CollectionPreview = ({ id, title, routeName, items }) => {