Understanding react key

栏目: IT技术 · 发布时间: 5年前

内容简介: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>
  </>
}

stable-key - CodeSandbox

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

  • key is an unique identifier for react element
  • key should be unique and stable . A react element with different key in 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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

颠覆营销

颠覆营销

陈杰豪、车品觉 / 中信出版社 / 2016-2 / 49.00元

对于大数据未来趋势的判断 车品觉 光阴荏苒,2015年在跌跌荡荡中成了过去式,对于大数据的产业来说过去这一年冒出了很多新的名词。但在我看来,真正的大数据应用和市场才刚刚开始萌芽,所以我希望大家先认清一个关键,那就是所有的数据都是基于应用而产生,而数据经过釆集及整合后又再落实到自身或其他应用情境中,大数据的创新价值可以来自新连接的数据、算法或者产品本身。 过去两年大数据的成长和智能......一起来看看 《颠覆营销》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试