12 Keyed lists

 

This chapter covers

  • Working with keyed lists of components
  • Working with keyed lists of elements
  • Updating the application instance
  • Publishing the new version of the framework

Components have internal state. This state is hidden from the outside world—not reflected in the virtual DOM tree that represents the view—and thus can’t be used to compare two component virtual DOM nodes. But to patch the view correctly, you must make sure that when you have a list of components, the reconciliation algorithm can distinguish among them.

Let’s look at an example. Suppose that you have a Counter component with a count state property, which can be initialized with a different value for each component instance:

const Counter = defineComponent({
  state(props) {
    return { count: props.initialCount }
  },

  render() {
    return h('p', {}, [`Count: ${this.state.count}`])
  },
})

Then you render a list of three Counter components, each of which has a different value for the count state:

h('div', {}, [
  h(Counter, { initialCount: 0 }),
  h(Counter, { initialCount: 1 }),
  h(Counter, { initialCount: 2 }),
])

Note that the value of each count state property isn’t reflected in the virtual DOM tree. That information is part of the component’s state, stored inside the Counter component instances. The rendered HTML would look like the following:

<div>
  <p>Count: 0</p>
  <p>Count: 1</p>
  <p>Count: 2</p>
</div>

12.1 The key attribute

 
 

12.1.1 Component nodes equality

 
 
 
 

12.1.2 Using the key attribute

 
 

12.1.3 Removing the key attribute from the props object

 
 
 
 

12.2 Extending the solution to element nodes

 
 

12.3 Using the key attribute

 
 
 

12.3.1 Mistake 1: Using the index as key

 
 
 

12.3.2 Mistake 2: Using the same key for different elements

 
 

12.4 The application instance

 
 

12.5 Publishing the framework

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage