简体   繁体   中英

deleting data from react-table

I am using react-table.js to take data from a form, but I want to be able to delete the data out of the table. The button is working so I know that is attached properly, but I can't seem to get it to delete. Here is the code

    handleDelete = item => {
    var newArr = [];
    const newState = this.props.documentation;
    for (var key in newState) {
      if (newState.hasOwnProperty(key)) {
        let data = newState[key];
        data.id = key;
        newArr.push(newState[key]);
      }
      const sliceArr = newArr.slice();
      if (sliceArr.indexOf(item) > -1) {
        sliceArr.slice(sliceArr.indexOf(item), 1);
      }
      console.log('New Array', sliceArr);
      this.setState({ data: sliceArr });
    }
  };

Along with the button I am attaching it to

Cell: row => (
          <div>
            <button onClick={() => this.handleDelete(row.id)}>Delete</button>
          </div>

You're looking for splice rather than slice:

  const spliceArr = newArr.slice();
  if (spliceArr.indexOf(item) > -1) {
    spliceArr.splice(spliceArr.indexOf(item), 1);
  }
  console.log('New Array', spliceArr);
  this.setState({ data: spliceArr });

Example:

const newArr = [1, 2, 3, 4]
// [1, 2, 3, 4] example
const spliceArr = newArr.slice()
// [1, 2, 3, 4] ok
spliceArr.slice(spliceArr.indexOf(3), 1)
spliceArr
// [1, 2, 3, 4] oops
spliceArr.splice(spliceArr.indexOf(3), 1)
spliceArr
// [1, 2, 4]    better

If that doesn't get you all the way there, you may want to update your question with the rendering (presumably JSX) of the table itself, as @MichaelBenin suggested.

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