React列表和键,缺少对象属性



在这个react教程中,作者使用了一段代码,从第61行开始:

const List = (props) => (
<ul>
{props.list.map((item) => (
<Item key={item.objectID} item={item} />
))}
</ul>
);

此函数是从第35行的const、App、<List list={stories} />中调用的。最后,故事是一个对象:

const stories = [
{
title: 'React',
url: 'https://reactjs.org/',
author: 'Jordan Walke',
num_comments: 3,
points: 4,
objectID: 0,
},
{
title: 'Redux',
url: 'https://redux.js.org/',
author: 'Dan Abramov, Andrew Clark',
num_comments: 2,
points: 5,
objectID: 1,
},
];

我对第61行感到困惑,特别是代码props.list.map。从对象stories来看,没有列表属性。然而,在第35行中,<List list={stories} />似乎暗示故事将被关键字list引用。

我的问题是:

  1. 这是怎么回事
  2. 为什么这种额外的复杂性是有益的(从全局角度讲,超出了本代码的上下文(

道具名为list,但该道具的值由stories常量填充。这样做的原因是为了使List组件具有通用性和灵活性。

如果您想将List用于其他目的,但在实际向它传递类或其他类型的列表时,必须向它传递一个名为stories的道具,这将是令人困惑的。

在您的情况下,只需理解props.list实际上就是stories

给定任何<Component prop={value} />,您可以使用prop:访问value

function Component(props) {
props.prop; // get value :O
}

许多人使用析构函数是因为它更容易阅读:

function Component({ prop }) {
prop; // get value too :O
}

此外,如果你有一个组件的道具对象,你可以将其展开:

const theProps = { prop: 42 };
return <Component {...theProps} /> // same as <Component prop={theProps.prop} />

此外,你不必破坏每一个道具,你可以把剩下的收集到一个正常使用的对象中:

function Component({ importantProp, ...notAsImportant }) {
importantProp; // easy access and to use
notAsImportant.prop; // you can still get the other props normally
}

最新更新