内容简介:Keys give the react elements a stableReact will throw a warning with the code above:Keys should be
Understanding React key
Keys give the react elements a stable identity
warning in array without key
import React from 'react';
function App() {
const persons = [‘mike’, ‘jason’, ‘sharky’];
return <ul>
{persons.map(p => {
return <li>{p}</li>
})}
</ul>
}
React will throw a warning with the code above: Warning: Each child in a list should have a unique "key" prop.
What keys to use?
Keys should be unique
and stable
Index ? Maybe, but only under some circumstances
Array index is unique across an array.
import React, { useState } from 'react';
function App() {
const persons = [‘mike’, ‘jason’, ‘sharky’];
return <ul>
{persons.map((p, index) => {
return <li key={index}>{p}</li>
})}
</ul>
}
However, if the order/number of items may change, array index is NOT stable
.
import React, { useState } from 'react';
function App() {
const [persons, setPersons] = useState(
['mike', 'jason', 'sharky']
);
const onAdd = () => {
setPersons(['fishman', ...persons])
}
return <>
<button onClick={onAdd}> Add fishman on top </button>
<ul>
{persons.map((p, index) => {
return <li key={index}><input type="checkbox"/>{p}</li>
})}
</ul>
</>
}
array-index-as-key - CodeSandbox
Ticking mike
and then clicking the add button will result in the loss of check status of mike
Stable
key
Usually we will have a unique and stable id
like property for each record from backend/database.
import React, { useState } from ‘react’;
export default function App() {
const [persons, setPersons] = useState(
[
{id: 'uywoejk', name: 'mike'},
{id: 'woeioqj', name: 'jason'},
{id: 'eljlkqd', name: 'sharky'}
]
);
const onAdd = () => {
setPersons([{
id: 'wuioeioe', name: 'fishman'
}, ...persons])
}
return <>
<button onClick={onAdd}> Add fishman on top </button>
<ul>
{
persons.map((p, index) => {
return <li key={p.id}><input type="checkbox"/>{p.name}</li>
})
}
</ul>
</>
}
Use key to unmount component
Use case: I have a select and input component. Each the select option changes, reset the input to default state,
import React, { useState } from “react”;
export default function App() {
const [option, setOption] = useState("");
return (
<>
<select onChange={e => setOption(e.target.value)}>
<option key="a">A</option>
<option key="b">B</option>
</select>
<input defaultValue="this is default"/>
<input key={option} defaultValue="this is default" />
</>
);
}
Conclusion
-
keyis an unique identifier for react element -
keyshould beuniqueandstable. A react element with differentkeyin different render phases will be considered as different elements. The old one will be unmounted and a new one is created. - Only use array indices as keys when the number/order of array items are unchanged across the whole app lifecycle.
-
Always prefer to use backend/database unique identifier id like property as
key
Notice
- If you want to follow the latest news/articles for the series of my blogs, Please 「Watch」 to Subscribe.
以上所述就是小编给大家介绍的《Understanding react key》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
编程语言实现模式
Terence Parr / 李袁奎、尧飘海 / 华中科技大学出版社 / 2012-3-20 / 72.00元
《编程语言实现模式》旨在传授开发语言应用(工具)的经验和理念,帮助读者构建自己的语言应用。这里的语言应用并非特指用编译器或解释器实现编程语言,而是泛指任何处理、分析、翻译输入文件的程序,比如配置文件读取器、数据读取器、模型驱动的代码生成器、源码到源码的翻译器、源码分析工具、解释器,以及诸如此类的工具。为此,作者举例讲解已有语言应用的工作机制,拆解、归纳出31种易于理解且常用的设计模式(每种都包括通......一起来看看 《编程语言实现模式》 这本书的介绍吧!