Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuck on "unique key" warning

I'm currently adapting a Mobx tutorial for a to-do app. link What I want to do is add a simple counter button to each rendered list item. I figured this would be pretty simple, but I must be making a syntactical error because I cannot get things to mesh properly. The main error I'm getting right now is that "Each child in an array or iterator must have a unique 'key' property". I figured I would solve this by adding in a uuid to each counter(the counter is what cause the error to begin appearing). Alas, I cannot seem to find a solution.

Here is the github repository for the app: https://github.com/Darthmaul/UmCount

Specifically this file is the one that has received the most modifications. I also added a "counterstore.js" file to keep the store of the counter intact(which seems to be failing).

Any help would be appreciated. At this point I just don't know what's wrong and what's right.

Thanks,

Andrew

like image 840
Darthmaul Avatar asked May 02 '17 19:05

Darthmaul


1 Answers

When you have a component which has an array of children, each of which might have its own children, not only the top-level children but also each child at a deeper level needs its own key.

The problem with doing

const Items = ({items}) => (
  <View style={{flex: 1, paddingTop: 10}}>
   {items.map((item, i) => {
        return (<View>
          <Text style={styles.item} key={i}>• {item} - {store.counter}</Text>
          <Button onPress={() => store.increment()} title="+1" color="#50EB5D" key={uuid()} />
          </View>
        )})
    }
  </View>
)

is that your Text and Button components have keys, but your Views do not.

React uses keys for reconciliation and finding the minimal change whenever a list of components changes. How you set keys here will affect the reconciliation policy when your array changes: You can set your View, Text and Button for each array element to have the same key if you know that whenever one of them changes, the entire row changes, but if each of them changes separately, then you should generate a unique ID for each of them.

React docs on reconciliation and keys.

like image 106
Pedro Castilho Avatar answered Nov 18 '22 06:11

Pedro Castilho