首页 > 解决方案 > 在 React JS 上删除后页面不刷新(需要手动重新加载)

问题描述

我是 React JS 的新手。我正在尝试使用 React 和 Spring 构建一个全栈 CRUD 应用程序。

我已经正确配置了 Delete REST API(在 Postman 上测试),它工作得很好。但是,当我单击页面上的删除按钮时,该条目不会自动从页面中删除。我必须执行手册页重新加载/刷新。重新加载页面后,不再显示该条目(已删除)。

可能是什么问题?

客户服务.js

deleteCustomer(customerId) {
        return axios.delete(customer_base_url + '/' + customerId);
    }

列出客户组件构造函数

class ListCustomerComponent extends Component {

    constructor(props){
        super(props)

        this.state = {
            customers: []
        }

        this.addCustomer = this.addCustomer.bind(this);
        this.editCustomer = this.editCustomer.bind(this);
        this.deleteCustomer = this.deleteCustomer.bind(this);
        this.viewCustomer = this.viewCustomer.bind(this);
    }

    editCustomer(id) {
        this.props.history.push(`/add-customer/${id}`);
    }

    deleteCustomer(id) {
        CustomerService.deleteCustomer(id).then( res => {
            this.setState({customers: this.state.customers.filter(customer => customer.id !== id)});
        });
    }

删除按钮

 <button style = {{ marginLeft: "10px"}} onClick = { () => this.deleteCustomer(customers.customerId)} className = "btn btn-danger"> Delete </button>

标签: javascriptreactjs

解决方案


在您的删除功能中,我注意到您使用了.customerId.

this.deleteCustomer(customers.customerId)} 

但是在您的过滤器功能中,您正在检查.id

this.state.customers.filter(customer => customer.id !== id)}

所以你的过滤功能应该是

this.state.customers.filter(customer => customer.customerId !== id)}

假设 .customerId 反映了客户的唯一标识符。


推荐阅读