简体   繁体   中英

flattenChildren(...) Reactjs warning

I am having a problem with updating data to google firebase

This is the constructor and handle function:

constructor() {
    super();
    this.state = {
    done: false
  }
 this.handleDoneChange = (event) => {
  this.setState({
    done: event.target.checked
  })
  Firebase.database().ref('/items').child(this.props.item.key).update(
    {
      done: event.target.checked
    }
  );
};

}

and the rendered html

<input type="checkbox"
                 checked={this.state.done}
                 onChange={this.handleDoneChange}/>

Whenever I check/uncheck the box it gives me a warning

warning.js:44 Warning: flattenChildren(...): Encountered two children with the same key, `.$-KJ1NOzrpaa5HmjRPulQ`. Child keys must be unique; when two children share a key, only the first child will be used.

but data are changed on firebase

Anyone have any idea of what is happening right here ? Thanks in advance!

React uses key s to figure out what to do when it reconciles the list. Seems like your render() function is fine -- could you check one or more levels above? I guess you have a parent component that uses .map(...) to render an array of components, and for each item of the array we need to provide a key . You can use an item's unique ID (should be possible to get it from Firebase) as its key.

More information can be found at https://facebook.github.io/react/docs/reconciliation.html#keys .

I found the solution to this if, it can help anyone for future reference. My mistake was in this:

componentDidMount() {
    Firebase.database().ref('/items').on("value", function (data) {
      this.setState({
        listOfItems: []
      });
      console.log(this.state.listOfItems)
      for (let key of Object.keys(data.val())) {
        this.setState({
          listOfItems: this.state.listOfItems.concat({key: key, text: data.val()[key].text, done: data.val()[key].done})
        })
      }

    }.bind(this));

  }

Since Google Firebase uses websocket and any change on UI is manifested on the database so it tries to add every time same thing from the code

this.setState({
      listOfItems: this.state.listOfItems.concat({key: key, text: data.val()[key].text, done: data.val()[key].done})
    })

So I came with a different solution and there is no error on adding/updating/removing data:

componentDidMount() {
  Firebase.database().ref('/items').on("value", function (data) {
    let list = [];
    for (let key of Object.keys(data.val())) {
      let item = data.val()[key];
      item.key = key;
      list.push(item);
    }
    this.setState({
      listOfItems: list
    })
  }.bind(this));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM