Reaction中的操作后刷新表

人气:548 发布:2022-10-16 标签: javascript crud reactjs

问题描述

嗨,我想做一个MERN应用程序

但是有一件事,当我更新或删除页面没有刷新时,我怎么做?我创建了一个索引,其中列出了我的所有条目

    // index.component.js

import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';

export default class Index extends Component {

  constructor(props) {
      super(props);
      this.state = {business: []};
    }
    componentDidMount(){
      axios.get('http://localhost:4000/business')
        .then(response => {
          this.setState({ business: response.data });
        })
        .catch(function (error) {
          console.log(error);
        })
    }
    tabRow(){
      return this.state.business.map(function(object, i){
          return <TableRow obj={object} key={i} />;
      });
    }

    render() {
      return (
        <div>
          <h3 align="center">Liste des billets</h3>
          <table className="table table-striped" style={{ marginTop: 20 }}>
            <thead>
              <tr>
                <th>Nom Prénom</th>
                <th>Poste</th>
                <th>Téléphone</th>
                <th colSpan="2">Action</th>
              </tr>
            </thead>
            <tbody>
              { this.tabRow() }
            </tbody>
          </table>
        </div>
      );
    }
  }

这是我的表格,其中包含选项

    // TableRow.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

class TableRow extends Component {

  constructor(props) {
        super(props);
        this.delete = this.delete.bind(this);
    }
    delete() {
        axios.get('http://localhost:4000/business/delete/'+this.props.obj._id)
            .then(console.log('Deleted'))
            .catch(err => console.log(err))
    }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.nomPrenom}
          </td>
          <td>
            {this.props.obj.posteEntreprise}
          </td>
          <td>
            {this.props.obj.numeroTel}
          </td>
          <td>
            <Link to={"/edit/"+this.props.obj._id} className="btn btn-primary">Editer</Link>
          </td>
          <td>
            <button onClick={this.delete} className="btn btn-danger">Supprimer</button>
          </td>
        </tr>
    );
  }
}

export default TableRow;

以下是我在此处尝试的内容,我的删除和更新有效,但只有在刷新页面时才会确认修改。

推荐答案

在删除功能中,您应该更新状态

     delete() {
        axios.get('http://localhost:4000/business/delete/'+this.props.obj._id)
            .then(()=>{
                        let list=this.state.business.filter((item)=>return (item.id===this.props.obj._id))
                        this.setState({business:list})}
            .catch(err => console.log(err))
    }

idk在您的案例中如何删除,因为我不知道列表,但应该是相似的

739