簡體   English   中英

使用 React 從表中刪除項目后重新加載表

[英]Reload table after deleting an item from it with React

使用 React.Js,我創建了一個刪除函數來從表中刪除一個項目。 刪除工作正常,但我想要做的是刪除后我希望表格動態更新以僅顯示剩余的項目。 現在刪除后我必須手動刷新頁面或轉到另一個頁面並回來查看刪除后留下的項目

這是迄今為止構建的代碼:

import React, { Component } from "react";
import { Card, Button, Select,/*  message, */ Form, Tooltip } from "antd";
import extraitMP3 from "./data";
import { arrayMove, SortableHandle } from "react-sortable-hoc";
import ContainerHeader from "components/ContainerHeader/index";
import { getExtraitMp3, hideMessageUpdate, showUpdateLoader, updateMp3Visibilite } from "appRedux/actions/Comedien";
import { deleteMp3Request } from "../../../appRedux/services/extraitMp3Service"
import { connect } from "react-redux";
import { NotificationContainer, NotificationManager } from "react-notifications";
import { userSignOut } from "appRedux/actions/Auth";
import { displayIcon } from '../../../util/Icon.js';
import CircularProgress from "components/CircularProgress";
import { Modal } from "antd";

const extraitMP32 = [extraitMP3];
const confirm = Modal.confirm;
const Option = Select.Option;

const DragHandle = SortableHandle(() =>
  <span className="gx-draggable-icon gx-pt-2">
    <i className="icon icon-menu" style={{ fontSize: 25 }} />
  </span>);

class ListExtrait extends Component {

  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState({
      extraitMP3: arrayMove(this.state.extraitMP3, oldIndex, newIndex),

    });
  };

  constructor() {
    super();
    this.state = {
      extraitMP3: extraitMP32[0],
      nombreMP3: {
        rechercheExtraits: 0,
        recherchePossible: 0,
        extraitFiche: 0,
        extraitFichePossible: '',
        extraitArchives: 0,
        extraitArchivesPossible: '',
      },
      loader: false,

    }
  }

  componentDidMount() {
    this.props.getExtraitMp3();
  }

  componentDidUpdate() {
  }

  static getDerivedStateFromProps(nextProps, prevState,/* nextProps2,prevState2 */) {
    if (nextProps.extraitMP3 !== prevState.extraitMP3 && nextProps.extraitMP3) {
      return { extraitMP3: nextProps.extraitMP3 };
    }
    else return null;
  }
  showDeleteConfirmation(value, id, index, thisHandler) {
    confirm({
      title: 'Voulez vous supprimer cette audio ?',
      content: '',
      okText: 'Oui, je confirme',
      okType: 'danger',
      cancelText: 'Non',
      onOk() {
        deleteMp3Request(id);
        const { extraitMP3 } = thisHandler.state;
        Object.keys(extraitMP3).splice(index, 1);
        NotificationManager.success("le fichier audio est supprimé avec succès !", "");
      },
      onCancel() {
      },
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {

      if (!err) {
        this.props.showUpdateLoader();
        this.props.updateMp3Visibilite(values);
      }
    });
  };

  render() {

    const { loader, extraitMP3 } = this.state;
    const selectOptions = new Map([
      [1, "Visible dans la recherche et sur ma fiche"],
      [2, "Visible sur ma fiche uniquement"],
      [3, "Masqué"],
    ]);
    console.log('extraitMP3', extraitMP3)


    function handleChangeSelect(value) {
      console.log(`selected ${value}`);
    }

    return (
      <div>
        {loader ? <CircularProgress className="gx-loader-400" /> : Object.keys(extraitMP3).map((ids, index) => {
          return (
            <Card>

              <li key={ids}>
                <Card styleName="gx-card-list icon icon-data-display gx-mr-2 gx-text-blue gx-fs-xl">
                  <div className="gx-media-body">
                    {extraitMP3[ids].Typenom}
                    &nbsp;
                  {extraitMP3[ids].TypeIcon != null &&
                      displayIcon(extraitMP3[ids].TypeIcon)
                    }
                  </div>

                  {Object.keys(extraitMP3[ids].TypeMp3List).map(idJson => {
                    return (
                      <div className="gx-main-content gx-mb-4">
                        <ContainerHeader match={this.props.match} />
                        <div className="gx-contact-item gx-dragndrop-item">

                          <DragHandle />

                          <div className="gx-col gx-job-title ">
                            {extraitMP3[ids].TypeMp3List[idJson].intitule}
                          </div>

                          {extraitMP3[ids].TypeMp3List[idJson].interpretation1Icon !== '' &&
                            <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation1Nom}>
                              {displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation1Icon)}
                            </Tooltip>
                          }

                          {extraitMP3[ids].TypeMp3List[idJson].interpretation2Icon !== '' &&
                            <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation2Nom}>
                              {displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation2Icon)}
                            </Tooltip>
                          }

                          {extraitMP3[ids].TypeMp3List[idJson].interpretation3Icon !== '' &&
                            <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].interpretation3Nom}>
                              {displayIcon(extraitMP3[ids].TypeMp3List[idJson].interpretation3Icon)}
                            </Tooltip>
                          }

                          {extraitMP3[ids].TypeMp3List[idJson].langueIcon !== '' &&
                            <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                              <Tooltip title={extraitMP3[ids].TypeMp3List[idJson].langueNom}>
                                <i className={`flag flag-24 gx-mr-2 ${extraitMP3[ids].TypeMp3List[idJson].langueIcon}`} />
                              </Tooltip>
                            </div>
                          }

                          <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                            <Select
                              showSearch
                              style={{ width: '100%' }}
                              placeholder="Selection la choix de votre numéro de téléphone "
                              optionFilterProp="children"
                              onChange={handleChangeSelect}
                              defaultValue={selectOptions.get(extraitMP3[ids].TypeMp3List[idJson].visibilite)}
                              filterOption={(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >
                              {[...selectOptions].map(([value, label]) => <Option value={value}> {label} </Option>)}
                            </Select>
                          </div>

                          <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                            <i className="icon icon-edit gx-fs-xl gx-text-gris" />
                          </div>

                          <div className="gx-col gx-job-title  gx-d-sm-flex gx-text-truncate gx-px-8">
                            <span className="gx-pointer">
                              <i className="icon icon-trash gx-pointer gx-text-danger gx-fs-xxl"
                                id={extraitMP3[ids].TypeMp3List[idJson].id}
                                onClick={e => this.showDeleteConfirmation(e.target.value, extraitMP3[ids].TypeMp3List[idJson].id, index, this)} />
                            </span>
                          </div>

                        </div>

                      </div>
                    )
                  })}
                  <NotificationContainer />

                  <Button type="primary" htmlType="submit" labelCol={{ xs: 24, sm: 5 }} wrapperCol={{ xs: 24, sm: 12 }}>
                    Enregistrer
                </Button>
                </Card>
              </li>
            </Card>
          )
        })}</div>
    )
  }
}

const VisibiliteFormMp3 = Form.create()(ListExtrait);

const mapStateToProps = ({ comedien }) => {
  const {
    extraitMP3,
    alertMessageUpdate,
    showMessageUpdate
  } = comedien;
  return {
    extraitMP3,
    alertMessageUpdate,
    showMessageUpdate
  }
};

export default connect(
  mapStateToProps,
  {
    userSignOut,
    getExtraitMp3,
    hideMessageUpdate,
    showUpdateLoader,
    updateMp3Visibilite
  })(VisibiliteFormMp3);

extraitMP3 是一個對象的對象,這就是為什么我使用Object.keys(extraitMP3)我不知道如何正確更新狀態。 這是觀點:

在此處輸入圖片說明

您應該將數據置於狀態,然后更改狀態。 更改狀態后,頁面會自動重新呈現並顯示您狀態的更改數據。 因此,在您的刪除功能中,只需刪除您選擇的數據並將剩余的數據交給您的州。

希望這會有所幫助,如果我無法清楚地解釋自己,請隨時提出問題。

我相信你可以通過調用類似的東西來做到這一點,然后從你的刪除中調用它

refreshMp3(){ 
this.setState({getExtraitMp3: !this.state.getExtraitMp3});}

React 的想法之一是使您要求的功能易於實現並且會自動更新。 我將從你的例子中抽象一下。 根據 UI 更新的內容來考慮您的數據。 這樣我們就可以簡化您的組件。 您有一些物品放在桌子上。 每一項都是一行,可以在一個數組中。 我們將該數組放入狀態。

class ListExtrait extends Component {
  constructor() {
    super();
    this.state = {
       rowsForTable: [...],
       somethingElse...
    }
    ...

然后在渲染方法的 JSX 中,您可以使用map渲染表行:

rowsForTable.map(item => <div/li/whatever>{item.name or something else}</div>

這樣,每當一個項目從rowsForTable消失時,組件就會自動更新它的視圖,並且表格行將是最新的。

您可以在單擊刪除按鈕時簡單地調用該函數,例如 deleteHandler。 在該函數中調用 api 來刪除該項目,然后在成功刪除后再次調用 api,該 api 將在一定時間間隔后從數據庫中顯示該項目。

Code: 

  import React, { Component } from 'react'

  export default class show_schedule extends Component {
    render() {
      state={

      }
      show_item_after_delete=()=>{
        setTimeout(()=>{
          axios.get(`http://127.0.0.1:8000/account/api/show_item/`).then(res=>{
          console.log('delete schedule data ',res.data)

        })
        },500)
      }
      deleteHandler=()=>{
        axios.delete(`http://127.0.0.1:8000/account/api/delete_item/${id}`).then(res=>{
          console.log(res.data)
        })
        this.show_item_after_delete()
      }
      return (
        <div>
          <button onClick={this.deleteHandler}>Delete</button>
        </div>
      )
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM