目录

列表&Key

# 07. 列表 & Key

如下代码,我们使用 map() (opens new window) 函数让数组中的每一项变双倍,然后我们得到了一个新的列表 doubled 并打印出来:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((number) => number * 2);
console.log(doubled);
1
2
3

在 React 中,把数组转化为元素 (opens new window)列表的过程是相似的。

# 渲染多个组件

const numbers = [1,2,3]
// 通过map方法将数值放入li,形成一个li标签组成的数值,在一次性放入ul
const listItems = numbers.map(number => {
  <li>{numbers}</li>
})

ReactDOM.render(
	<ul>{listItems}</ul>
  document.getElementById('root')
)
1
2
3
4
5
6
7
8
9
10

# 基础列表组件

将列表组合成一个组件:

function NumberList(props){
  const numbers = props.numbers
  const listItems = numbers.map(number => {
    // 记得给列表元素添加key
    <li key={number.toString()}>
    	{number}
    </li>
  })

  return (
  	<ul>{listItems}</ul>
  )
}

const numbers = [1,2,3]
ReactDOM.render(
	<NumberList numbers={numbers} />,
  document.getElementById('root')
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# key

key 帮助 React 识别哪些元素改变了,比如被添加或删除。因此你应当给数组中的每一个元素赋予一个确定的标识。

一个元素的 key 最好是这个元素在列表中拥有的一个独一无二的字符串通常,我们使用数据中的 id 来作为元素的 key

const todoItems = todos.map((todo) =>
  <li key={todo.id}>
       {todo.text}
  </li>
);
1
2
3
4
5

当元素没有确定 id 的时候,万不得已你可以使用元素索引 index 作为 key

const todoItems = todos.map((item, index) =>
  // 只有item中没有id 才用index代替
  <li key={index}>
        {item.text}
  </li>
);
1
2
3
4
5
6

如果列表项目的顺序可能会变化,我们不建议使用索引来用作 key 值,因为这样做会导致性能变差,还可能引起组件状态的问题。

如果你选择不指定显式的 key 值,那么 React 将默认使用索引用作为列表项目的 key 值

# 用 key 提取组件 (在map方法内设置key)

元素的 key 只有放在就近的数组上下文中才有意义。

例子:不正确的使用 key 的方式

function ListItem(props) {
  const value = props.value;
  return (
    // 错误!你不需要在这里指定 key:
    <li key={value.toString()}>
      {value}
    </li>
  );
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // 错误!元素的 key 应该在这里指定:
    <ListItem value={number} />
  );

  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

一个好的经验法则是:map() 方法中的元素需要设置 key 属性

#

# 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')
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 不能用key当props名传给子组件

key 会传递信息给 React ,但不会传递给你的组件。如果你的组件中需要使用 key 属性的值,请用其他属性名显式传递这个值:

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title} />
);
1
2
3
4
5
6

上面例子中,Post 组件可以读出 props.id,但是不能读出 props.key

# 在 JSX 中嵌入 map()

JSX 允许在大括号中嵌入任何表达式 (opens new window),所以我们可以内联 map() 返回的结果:

function NumberList(props) {
  const numbers = props.numbers;
  return (
    <ul>
      {
        numbers.map((number) =>
            <ListItem key={number.toString()} value={number} />
        )
      }
    </ul>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12

这么做有时可以使你的代码更清晰,但有时这种风格也会被滥用。

就像在 JavaScript 中一样,何时需要为了可读性提取出一个变量,这完全取决于你。但请记住,如果一个 map() 嵌套了太多层级,那可能就是你提取组件 (opens new window)的一个好时机。

上次更新: 2023/07/11, 15:43:07
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>