@SerGeGR

Как удалить комментарий из localstorage в React?

Подскажите, как удалить комментария из localStorage вместе с удалением из общего списка (функция removeComment)?
import React, { Component } from "react";
import CommentSection from "./CommentSection";
import Form from "./Form";

class App extends Component {
  state = {
    comments: []
  };

  componentDidMount() {
    if (localStorage.getItem("state")) {
      this.setState({ ...JSON.parse(localStorage.getItem("state")) });
    }
  }

  //Добавление комментария
  handleSubmit = comment => {
    this.setState({ comments: [...this.state.comments, comment] }, () =>
      localStorage.setItem("state", JSON.stringify(this.state))
    );
  };

  //Удаление комментария
  removeComment = index => {
    const { comments } = this.state;

    this.setState({
      comments: comments.filter(
        (comment, i) => {
          return i !== index;
        },
        () => localStorage.setItem("state", JSON.stringify(this.state))
      )
    });
  };

  render() {
    const { comments } = this.state;

    return (
      <div className="container">
        <Form handleSubmit={this.handleSubmit} />
        <CommentSection
          commentData={comments}
          removeComment={this.removeComment}
        />
      </div>
    );
  }
}

export default App;
  • Вопрос задан
  • 248 просмотров
Решения вопроса 1
0xD34F
@0xD34F Куратор тега React
this.setState({
  comments: comments.filter(
    (comment, i) => {
      return i !== index;
    },
    () => localStorage.setItem("state", JSON.stringify(this.state))
  )
});

Действительно, второй параметр filter, второй параметр setState - разница невелика, по сути одно и то же, должно же работать как надо. Или всё-таки нет?
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы