首页 > 解决方案 > 如何在删除项目后使用类更新/重新渲染 React 列表

问题描述

感谢您的任何支持。我正在学习 React,需要解决的问题是在从列表中删除项目后,我无法让 React 重新渲染。

首先,我想说我已经按照我找到的答案进行了搜索,但仍然没有运气。

场景是我使用 React 从 API 中获取列表并在同一个屏幕中呈现它,并使用一个表单来编辑和列出列表中每个项目的特定信息(字段只是名称和姓氏)。该列表显示有一个用于编辑的按钮,用于编辑表单,另一个按钮用于删除。该列表仅显示两个字段,即名称和姓氏,它们是使用来自 reacstrap 的 ListGroupItem 显示的,当 onClick 仅使用该表单进行列表时。我也有添加项目的逻辑。

我能够毫无问题地添加、更新、列出并正确重新渲染。但是,在删除时,我只能从 API 中删除该项目,但我必须手动重新渲染以显示更新列表

import React, { Component } from "react";

import { Button, Container, Row, Col } from "reactstrap";

import ListBebes from "./components/ListBebes";

import AddBebeForm from "./components/AddBebeForm";

import EditBebeForm from "./components/EditBebeForm";

import { fetchBebes, fetchBebe, addBebe, deleteBebe } from "./api";

import Websocket from "react-websocket";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      bebes: [],
      bebe: {},
      current_bebe_id: 0,
      is_creating: true,
      is_fetching: true,
      is_justRead: true,
      has_updated: false,
    };
    this.socket = React.createRef();
    this.focusSocket = this.focusSocket.bind(this);
    this.handleItemClick = this.handleItemClick.bind(this);
    this.handleEditClick = this.handleEditClick.bind(this);
    this.handleDeleteClick = this.handleDeleteClick.bind(this);
    this.handleAddBebe = this.handleAddBebe.bind(this);
    this.getData = this.getData.bind(this);
    this.handleSaveBebe = this.handleSaveBebe.bind(this);
    this.handleOnNombresChange = this.handleOnNombresChange.bind(this);
    this.handleOnApellidosChange = this.handleOnApellidosChange.bind(this);
  }

  componentDidMount() {
    this.getData();
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.has_updated === true) {
      this.getData();
      this.setState({ has_updated: false });
    }
  }

  focusSocket() {
    this.socket.current.focus();
  }

  async getData() {
    let data = await fetchBebes();
    this.setState({ bebes: data, is_fetching: false });
  }

  async handleItemClick(id) {
    let selected_bebe = await fetchBebe(id);
    this.setState((prevState) => {
      return {
        is_creating: false,
        is_justRead: true,
        current_bebe_id: id,
        bebe: selected_bebe,
      };
    });
  }

  async handleEditClick(id) {
    let selected_bebe = await fetchBebe(id);

    this.setState((prevState) => {
      return {
        is_creating: false,
        is_justRead: false,
        current_bebe_id: id,
        bebe: selected_bebe,
      };
    });
  }

  async handleDeleteClick(id) {
    let antesBebes = [...this.state.bebes];
    console.log(antesBebes);
    let index = antesBebes.findIndex((i) => i.id === id);
    console.log(`the index es ${index} y el id es ${id}`);
    await deleteBebe(id);
    antesBebes.splice(index, 1);
    console.log(antesBebes);
    this.setState({ bebes: [...antesBebes], has_updated: true });
    //this.setState({ bebes: this.state.bebes, has_updated: true });
    //console.log(antesBebes);
    console.log("it was deleted...");
    //window.location.reload();
    //this.setState((prevState) => {
    //return {
    //bebes: antesBebes,
    //has_updated: true,
    //};
    //});
    //this.getData();
  }

  handleAddBebe() {
    this.setState((prevState) => {
      return { is_creating: true };
    });
  }

  async handleSaveBebe(data) {
    await addBebe(data);
    await this.getData();
  }

  handleData(data) {
    let result = JSON.parse(data);
    let current_bebe = this.state.bebe;
    if (current_bebe.id === result.id) {
      this.setState({ bebe: result });
    }
  }

  handleOnNombresChange(e) {
    let nombres = e.target.value;
    let current_bebe = this.state.bebe;
    current_bebe.nombres = nombres;

    this.setState({
      bebe: current_bebe,
      has_updated: true,
    });

    const socket = this.socket.current;
    socket.state.ws.send(JSON.stringify(current_bebe));
  }

  handleOnApellidosChange(e) {
    let apellidos = e.target.value;
    let current_bebe = this.state.bebe;
    current_bebe.apellidos = apellidos;

    this.setState({
      bebe: current_bebe,
      has_updated: true,
    });

    //const socket = this.refs.socket;
    const socket = this.socket.current;
    socket.state.ws.send(JSON.stringify(current_bebe));
  }

  render() {
    return (
      <>
        <Container>
          <Row>
            <Col xs="10">
              <h2>Hello</h2>
            </Col>
            <Col>
              <Button color="primary" onClick={this.handleAddBebe}>
                Create a new note
              </Button>
            </Col>
          </Row>
          <Row>
            <Col xs="4">
              {this.state.is_fetching ? (
                "Loading..."
              ) : (
                <ListBebes
                  bebes={this.state.bebes}
                  handleItemClick={(id) => this.handleItemClick(id)}
                  handleEditClick={(id) => this.handleEditClick(id)}
                  handleDeleteClick={(id) => this.handleDeleteClick(id)}
                ></ListBebes>
              )}
            </Col>
            <Col xs="8">
              {this.state.is_creating ? (
                <AddBebeForm handleSave={this.handleSaveBebe} />
              ) : (
                <EditBebeForm
                  handleNombresChange={this.handleOnNombresChange}
                  handleApellidosChange={this.handleOnApellidosChange}
                  bebe={this.state.bebe}
                  soloLeer={this.state.is_justRead}
                />
              )}
              <Websocket
                ref={this.socket}
                url="ws://127.0.0.1:8000/ws/bebes"
                onMessage={this.handleData.bind(this)}
              />
            </Col>
          </Row>
        </Container>
      </>
    );
  }
}
export default App;

标签: reactjs

解决方案


您可以调试以下几行吗?和打印[...antesBebes]| this.state.bebesantesBebes 线后3

我对这些行有一些暂停,但无法调试它们,因为您尚未在此处添加所有组件。


1    antesBebes.splice(index, 1);
2    console.log(antesBebes);
3    this.setState({ bebes: [...antesBebes], has_updated: true });

我的建议是使用以下方法之一来管理您在 React 应用程序中的状态:

  1. React Hooks - 推荐用于像你这样的小型应用程序链接
  2. React Redux——链接

推荐阅读