简体   繁体   中英

Deleting Elements in array by index using Immer in React

I'm building this component using React where I can Add Delete and edit lessons and sections using immer library. However, when I add a new section I cant seem to delete a specific Lesson in the section, it deletes the last lesson created. And Deleting a specific section is not working as well. Can anyone give me a hint to this problem?

These are the two deletion function that are giving me a hard time:

 remove = (sectionIndex, lessonIndex) => {
    const nextState = produce(this.state, (draftState) => {
      draftState.list[sectionIndex].lessons.splice(lessonIndex, 1);
    });
    this.setState(nextState);
    this.id++;
  };

  deletesection(sectionIndex, i) {
    const nextState = produce(this.state, (draftState) => {
      draftState.list[sectionIndex].section.splice(i, 1);
    });
    this.setState(nextState);
    this.id++;
  }

Here is the a link to the sandbox reproduction code: https://codesandbox.io/s/serene-forest-hpv7r?file=/src/TestClonereact.jsx

remove actually seemed to be working for me, but I spotted some errors with deletesection :

  • The function takes two arguments (both of which seem to be the section index), but you only call it with one.
  • It's not an arrow function, so it will have its own this and won't be able to access this.state .
  • You are accessing a property .section which does not seem to exist.
  • Instead of splice you would want to remove the whole section object from the draftState.list array.
deletesection = (sectionIndex) => {
  const nextState = produce(this.state, (draftState) => {
    delete draftState.list[sectionIndex];
  });
  this.setState(nextState);
}

My personal preference would be use curried functions rather than passing the sectionIndex all the way down to the Lesson component. Also you can use produce inside a setState callback rather than accessing this.state directly. But those are just suggestions. Here's my tweaked version:

import React from "react";
import "./styles.css";
import EdiText from "react-editext";
import produce from "immer";
import { v4 as uuid } from "uuid";

const Lesson = ({ lesson, onSave, remove }) => {
  const { id } = lesson;
  return (
    <div key={id} id={`sectionlesson-${id}`}>
      <div className="section-titles">
        <i className="material-icons" id="iconsectionlist" type="button">
          list
        </i>

        <EdiText
          type="text"
          value="Lesson Title"
          onSave={onSave}
          key={id}
          id={`lesson-${id}`}
        />

        <i className="material-icons" id="iconsectiondel" type="button">
          text_fields
        </i>
        <i className="material-icons" id="iconsectiondel" type="button">
          smart_display
        </i>
        <i
          className="material-icons"
          id="iconsectiondel"
          onClick={remove}
          type="button"
        >
          delete
        </i>
      </div>
      <div className="testh"></div>
    </div>
  );
};

const Section = ({ section, onSave, remove, addlesson, deletesection }) => {
  const { id } = section;
  return (
    <div key={id} id={`sds-${id}`}>
      <div className="course-structure-form" key={id} id={`csf1-${id}`}>
        <div className="section-heading">
          <i className="material-icons" id="iconsection">
            api
          </i>

          <EdiText type="text" value="Section Title" onSave={onSave} />
        </div>

        {section.lessons.map((lesson, lessonIndex) => (
          <Lesson
            key={lesson.id}
            lesson={lesson}
            remove={remove(lessonIndex)}
            onSave={onSave}
          />
        ))}

        <div className="addnewlesson" onClick={addlesson}>
          <i
            className="material-icons"
            id="iconsectionde"
            role="button"
            type="button"
          >
            add_circle
          </i>

          <span>Add New Lesson</span>
        </div>
        <button onClick={deletesection}>Delete Section</button>
      </div>
    </div>
  );
};

class TestClonereact extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: []
    };
  }

  onSave = (val) => {
    console.log("Edited Value -> ", val);
  };

  lesson({ id }) {}

  addsection = () => {
    this.setState(
      produce((draftState) => {
        draftState.list.push({ id: uuid(), lessons: [] });
      })
    );
  };

  addlesson = (sectionIndex) => () => {
    this.setState(
      produce((draftState) => {
        // needs to have a unique id
        draftState.list[sectionIndex].lessons.push({ id: uuid() });
      })
    );
  };

  remove = (sectionIndex) => (lessonIndex) => () => {
    this.setState(
      produce((draftState) => {
        draftState.list[sectionIndex].lessons.splice(lessonIndex, 1);
      })
    );
  };

  deletesection = (sectionIndex) => () => {
    this.setState(
      produce((draftState) => {
        delete draftState.list[sectionIndex];
      })
    );
  };

  render() {
    return (
      <div>
        {this.state.list.map((section, i) => (
          <Section
            key={section.id}
            section={section}
            remove={this.remove(i)}
            addlesson={this.addlesson(i)}
            onSave={this.onSave}
            deletesection={this.deletesection(i)}
          />
        ))}

        <div className="add-section-button-structure">
          <button className="tablink" onClick={this.addsection}>
            Add New Section
          </button>
          <button className="tablink">Clear</button>
          <button className="tablink">Preview</button>
          <button className="tablink">Submit</button>
        </div>
      </div>
    );
  }
}

export default TestClonereact;

Code Sandbox Link

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