我正在构建一个React web应用程序,该应用程序在连接到数据库的表上执行CRUD操作。我在React组件中使用axios对后端控制器进行ajax调用。Customers组件显示my表中的记录列表。当我从数据库中创建、删除或编辑记录时,Customers组件不会自动刷新。我必须刷新页面才能获得数据库中更新的记录。我看过提升状态,但我不明白为什么它不能工作,因为Customers组件已经是父组件了。
import React, { Component } from 'react';
import axios from 'axios';
import { Table, Header } from 'semantic-ui-react';
import EditCustomerModal from './EditCustomerModal';
import AddCustomerModal from './AddCustomerModal';
import DeleteCustomerModal from './DeleteCustomerModal';
export class Customers extends Component {
constructor(props) {
super(props);
this.state = { customers: [] };
}
componentDidMount() {
this.populateCustomerData();
}
render() {
let customers = this.state.customers;
return (
<div>
<Header as='h2'>Customer Table</Header>
<p>This component demonstrates CRUD operations from the customer table.</p>
<AddCustomerModal />
<Table striped>
<Table.Header>
<Table.Row>
<Table.HeaderCell>ID</Table.HeaderCell>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Address</Table.HeaderCell>
<Table.HeaderCell textAlign="center">Actions</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{customers.map((customer) => {
return (
<Table.Row key={customer.id}>
<Table.Cell>{customer.id}</Table.Cell>
<Table.Cell>{customer.name}</Table.Cell>
<Table.Cell>{customer.address}</Table.Cell>
<Table.Cell textAlign="center">
<EditCustomerModal details={customer} />
<DeleteCustomerModal customerID={customer.id} />
</Table.Cell>
</Table.Row>
)
})}
</Table.Body>
</Table >
</div>
);
}
populateCustomerData = () => {
axios.get("Customers/GetCustomers")
.then((result) => {
this.setState({ customers: result.data })
})
.catch((error) => {
console.log(error);
});
}
}
发布于 2020-10-26 13:24:17
您需要将一个changeState函数从Customers组件传递到modals,并在crud操作完成后调用它。
或
您可以将populateCustomerData函数传递给模态函数,并让它们在crud操作完成后调用该函数。
https://stackoverflow.com/questions/64537459
复制相似问题