【问题标题】:Page is not refreshing after Delete on React JS (Requires manual reload)在 React JS 上删除后页面不刷新(需要手动重新加载)
【发布时间】:2021-04-10 03:54:45
【问题描述】:

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

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

可能是什么问题?

CustomerService.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>

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

    this.deleteCustomer(customers.customerId)} 
    

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

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

    所以你的过滤功能应该是

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多