1、使用 [map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) 函数遍历列表、数组
A.单纯的渲染遍历数据
const numbers = [1, 2, 3, 4, 5];const listItems = numbers.map((number) =><li>{number}</li>);
B.带Key的渲染-方便CRUD
- React通过key识别哪些元素改变了,比如被添加或删除。给数组中的每一个元素赋予一个确定的标识。
- 一个元素的 key 最好是这个元素在列表中拥有的一个独一无二的字符串。通常使用数据中的 id 来作为元素的 key。
- 当元素没有确定 id 的时候,可以使用元素索引 index 作为 key。
- 如果不显式的指定 key 值,那么 React 将默认使用索引用作为列表项目的 key 值。
如果列表项目的顺序可能会变化,不建议使用索引来用作 key 值,因为这样做会导致性能变差,还可能引起组件状态的问题。const numbers = [1, 2, 3, 4, 5];const listItems = numbers.map((number, index) =><li key={index}>{number}</li>);
a.用 key 提取组件
元素的 key 只有放在就近的数组上下文中才有意义。
提取出一个ListItem组件,你应该把 key 保留在数组中的这个<ListItem />元素上,而不是放在ListItem组件中的<li>元素上。例子:不正确的使用 key 的方式
```jsx function ListItem(props) { const value = props.value; return ( // 错误!你不需要在这里指定 key: - {value} ); }
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
// 错误!元素的 key 应该在这里指定:
-
{listItems}
const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
<a name="I22BI"></a>#### **例子:正确的使用 key 的方式**```jsxfunction ListItem(props) {// 正确!这里不需要指定 key:return <li>{props.value}</li>;}function NumberList(props) {const numbers = props.numbers;const listItems = numbers.map((number) =>// 正确!key 应该在数组的上下文中被指定<ListItem key={number.toString()}value={number} />);return (<ul>{listItems}</ul>);}const numbers = [1, 2, 3, 4, 5];ReactDOM.render(<NumberList numbers={numbers} />,document.getElementById('root'));
b.key 只是在兄弟节点之间必须唯一
数组元素中使用的 key 在其兄弟节点之间应该是独一无二的。不需要是全局唯一的。当生成两个不同的数组时,可以使用相同的 key 值
function Blog(props) {const sidebar = (<ul>{props.posts.map((post) =><li key={post.id}>{post.title}</li>)}</ul>);const content = props.posts.map((post) =><div key={post.id}><h3>{post.title}</h3><p>{post.content}</p></div>);return (<div>{sidebar}<hr />{content}</div>);}const posts = [{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},{id: 2, title: 'Installation', content: 'You can install React from npm.'}];ReactDOM.render(<Blog posts={posts} />,document.getElementById('root'));
key 会传递信息给 React ,但不会传递给自定义的组件。如果自定义的组件中需要使用 key 属性的值,可以用其他属性名显式传递这个值
const content = posts.map((post) =><Postkey={post.id}id={post.id}title={post.title} />);
Post 组件可以读出 props.id,但是不能读出 props.key。
2、在 JSX 中嵌入 map()
function NumberList(props) {const numbers = props.numbers;const listItems = numbers.map((number) =><ListItem key={number.toString()}value={number} />);return (<ul>{listItems}</ul>);}
function NumberList(props) {const numbers = props.numbers;return (<ul>{numbers.map((number) =><ListItem key={number.toString()}value={number} />)}</ul>);}
