如何在删除项目后使用类更新/重新呈现React列表



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

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

场景是,我使用React从API获取一个列表,并在同一屏幕中使用一个表单呈现它,用于编辑和列出列表中每个项的特定信息(字段仅为名称和姓氏(。该列表显示了一个用于编辑的按钮,该按钮使表单进行编辑,另一个按钮用于删除。该列表只显示两个字段,即name和lastname,这两个字段是使用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;

您能调试以下行吗?并在第3行之后打印[...antesBebes]|this.state.bebesantesBebes

我对这些行有一些暂停,但无法调试它们,因为您还没有在这里添加所有组件。


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

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

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

我找到了解决方案。碰巧我把代码放在delete函数handleDeleteClick((和componentDidUpdate中,把事情搞砸了。删除的最终代码是:

async handleDeleteClick(id) {
let antesBebes = [...this.state.bebes];
let index = antesBebes.findIndex((i) => i.id === id);
await deleteBebe(id);
antesBebes.splice(index, 1);
await this.setState({ bebes: antesBebes });
}

这段代码可能还有其他问题,但就最初的目标而言,这解决了问题。

最新更新