Lists and Keys
2020-08-14 本文已影响0人
bestCindy
const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
- We need to set a key to each item, keys helpReact identify which items have changed, are added, or are removed
- When you don't have stable IDs for rendered items, you may use the item index as a key
const todoItems = todos.map((todo, index) => {
<li key={ index }>
{ todo.text }
</li>
});
- It's is not recommended, and if you not to assign an explicit key to list items then React will default to using indexed as keys
- Rember the element inside the
map()
call need keys - there is no need to set a key in belos example
function ListItem(props) {
const value = props.value;
return (
// Wrong! There is no need to specify the key here:
<li key={value.toString()}>
{value}
</li>
);
}
- embedding any expression
function NumberList(props) {
const number = props.numbers;
const listItems = numbers.map(number => {
<listItems key={number.toString()} value ={number} />
});
return (
<ul>
{listItem}
</ul>
);
}
we could inline the map()
in curly braces
function NumberList(props) {
const numbers = props.numbers;
return(
<ul>
{ numbers.map(number => {
<ListItem key={number.toString()} value={number} />
}) }
</ul>
);
}