Useful JS Tips

#02 - Keys in children components are important

2016-01-02 by @loverajoel

The key is an attribute that you must pass to all components created dynamically from an array. It’s a unique and constant id that React uses to identify each component in the DOM and to know whether it’s a different component or the same one. Using keys ensures that the child component is preserved and not recreated and prevents weird things from happening.

Key is not really about performance, it’s more about identity (which in turn leads to better performance). Randomly assigned and changing values do not form an identity Paul O’Shannessy

  • Use an existing unique value of the object.
  • Define the keys in the parent components, not in child components
//bad
...
render() {
	<div key={% raw %}{{item.key}}{% endraw %}>{% raw %}{{item.name}}{% endraw %}</div>
}
...

//good
<MyComponent key={% raw %}{{item.key}}{% endraw %}/>
//bad
<MyComponent key={% raw %}{{Math.random()}}{% endraw %}/>
<<返回目录