mardi 18 avril 2017

React Checkbox Stays Checked Even After Component is Unmounted

So, I have a list of items with checkboxes, just like a classic todo application.

enter image description here

When I select "Johnny" and then click, "Delete Selected Records," Johnny does go away. Yay!

enter image description here

But, once Johnny is gone Renee is checked, now.

enter image description here

I did NOT click on Renee. I only clicked on Johnny, but once Johnny was deleted Renee became checked. wtf?

Obviously, something is happening where the checkbox DOM is staying true of checked, even though I just wiped out the checkbox in its place.

I tried solving this through updating the state in componentWillUnmount, but that didn't work.

import React, {Component} from 'react';

class Person extends Component {

  constructor(props) {
    super(props);

    this.state = {
      checked: false
    }

    this.checkboxToggle = this.checkboxToggle.bind(this);
  }

  checkboxToggle() {
    this.setState({ checked: !this.state.checked }, () => {
      if (this.state.checked === false) {
        console.log("Checked should be FALSE");
      }
      else if (this.state.checked === true) {
        console.log("Checked should be TRUE");
        this.props.setForDelete(this.props.person._id);
      }
    });
  }

  componentWillUnmount() {
    this.setState({ checked: false });
  }

    render() {
        return (
          <div>
            <input type="checkbox" name="person" checked={this.state.checked} onChange={this.checkboxToggle} />
            {this.props.person.name} ({this.props.person.age})
          </div>
        );
    }
}

export default Person;

Everything else in the Person component is working fine. How do I get all the checkboxes to become unchecked once I have deleted any of the records?




Aucun commentaire:

Enregistrer un commentaire