【问题标题】:Reload table after deleting an item from it with React使用 React 从表中删除项目后重新加载表
【发布时间】:2019-06-26 09:43:47
【问题描述】:

使用 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) 的原因 我不知道如何正确更新状态。 这是视图:

【问题讨论】:

    标签: javascript reactjs react-native redux react-redux


    【解决方案1】:

    您应该将数据置于状态,然后更改状态。更改状态后,页面会自动重新渲染并显示您状态的更改数据。 因此,在您的删除功能中,只需删除您选择的数据并将剩余数据提供给您的状态。

    希望这会有所帮助,如果我无法清楚地解释自己,请随时提出问题。

    【讨论】:

      【解决方案2】:

      我相信你可以通过调用类似的东西来做到这一点,然后从你的删除中调用它

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

      【讨论】:

        【解决方案3】:

        React 的一个想法是让您要求的功能易于实现,并且会自动更新。我将从你的例子中抽象一点。根据 UI 的更新来考虑您的数据。这样我们可以简化您的组件。您有一些放在桌子上的物品。每个项目都是一行,可以在一个数组中。我们将该数组置于状态中。

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

        然后在 JSX 的 render 方法中你可以使用 map 渲染表格行:

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

        这样,每当一个项目从rowsForTable 消失时,组件将自动更新它的视图并且表格行将是最新的。

        【讨论】:

          【解决方案4】:

          您可以简单地在单击删除按钮时调用该函数,例如 deleteHandler。在该函数上调用您为删除项目所做的 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>
                )
              }
            }
          

          【讨论】:

          • 它会工作,但最后一项不会删除...
          猜你喜欢
          • 1970-01-01
          • 2021-09-02
          • 2022-12-07
          • 1970-01-01
          • 2021-09-28
          • 1970-01-01
          • 2017-02-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多