删除按钮后react刷新页面

IT技术 reactjs use-effect
2021-05-05 07:41:52

我的应用程序的删除功能工作正常,但是它需要用户在用户单击删除按钮后手动刷新页面,以便查看我数据库中的新元素列表。我想在点击事件后自动刷新。我正在为这个项目使用 React 钩子。但是,如果我删除,我找到了一种解决方案,useEffect's []但在我的后端显示,它疯狂地请求。我不知道,删除 useffect 的[]是否明智

这是它从后端获取数据并将props传递给另一个组件的组件

 import React, { useState, useEffect } from "react";
    import axios from "axios";
    import Table from "../Table/Table";
    import "./Display.css";
    const Display = () => {
      const [state, setState] = useState({ students: [], count: "" });
      const [searchItem, setsearchItem] = useState({
        item: ""
      });

      const Search = e => {
        setsearchItem({ item: e.target.value });
      };

      useEffect(() => {
        axios
          .get("/students")
          .then(response => {
            setState({
              students: response.data.students,
              count: response.data.count
            });
          })
          .catch(function(error) {
            console.log(error);
          });
      }, []); //If I remove this square brackets, it works 
      const nameFilter = state.students.filter(list => {
        return list.name.toLowerCase().includes(searchItem.item.toLowerCase());
      });

      return (
        <div>
          <h3 align="center">Student tables</h3>
          <p align="center">Total students: {state.count}</p>
          <div className="input-body">
            <div className="row">
              <div className="input-field col s6">
                <input placeholder="search student" onChange={Search} />
              </div>
            </div>
          </div>

          <table className="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Date of birth</th>
                <th>Address</th>
                <th>Zipcode</th>
                <th>City</th>
                <th>Phone</th>
                <th>Email</th>
                <th colSpan="2">Action</th>
              </tr>
            </thead>
            {nameFilter.map((object, index) => {
              return (
                <tbody key={index}>
                  <Table obj={object} /> //In here I am passing the props to the another component.
                </tbody>
              );
            })}
          </table>
        </div>
      );
    };

    export default Display;

这是接收props的第二个组件。

import React, { useState } from "react";
import { Link } from "react-router-dom";
import axios from "axios";

const Table = props => {
  const removeData = () => {
    axios
      .delete("/students/" + props.obj.id)
      .then(console.log("Deleted"))
      .catch(err => console.log(err));
  };

  return (
    <React.Fragment>
      <tr>
        <td>{props.obj.name}</td>
        <td>{props.obj.birthday}</td>
        <td>{props.obj.address}</td>
        <td>{props.obj.zipcode}</td>
        <td>{props.obj.city}</td>
        <td>{props.obj.phone}</td>
        <td>{props.obj.email}</td>
        <td>
          <Link
            to={"/edit/" + props.obj.id}
            className="waves-effect waves-light btn"
          >
            Edit
          </Link>
        </td>
        <td>
          <button onClick={removeData} className="waves-effect red btn ">
            Remove
          </button>
        </td>
      </tr>
    </React.Fragment>
  );
};

export default Table;
2个回答

[]useEffect钩是一个依赖阵列以触发到运行的效果。如果您想触发效果(不要无情地关闭),您可以创建一个新变量来触发该效果运行。

import React, { useState, useEffect } from "react";
import axios from "axios";
import Table from "../Table/Table";
import "./Display.css";

const Display = () => {
  const [state, setState] = useState({ students: [], count: "" });
  const [requestData, setRequestData] = useState(new Date());
  const [searchItem, setsearchItem] = useState({
    item: ""
  });

  const Search = e => {
    setsearchItem({ item: e.target.value });
  };

  useEffect(() => {
    axios
      .get("/students")
      .then(response => {
        setState({
          students: response.data.students,
          count: response.data.count
        });
      })
      .catch(function(error) {
        console.log(error);
      });
  }, [requestData]);

  const nameFilter = state.students.filter(list => {
    return list.name.toLowerCase().includes(searchItem.item.toLowerCase());
  });

  return (
    <div>
      <h3 align="center">Student tables</h3>
        <p align="center">Total students: {state.count}</p>
        <div className="input-body">
          <div className="row">
            <div className="input-field col s6">
              <input placeholder="search student" onChange={Search} />
            </div>
          </div>
        </div>
        <table className="table table-striped">
          <thead>
            <tr>
              <th>Name</th>
              <th>Date of birth</th>
              <th>Address</th>
              <th>Zipcode</th>
              <th>City</th>
              <th>Phone</th>
              <th>Email</th>
              <th colSpan="2">Action</th>
            </tr>
          </thead>
          {nameFilter.map((object, index) => {
            return (
              <tbody key={index}>
                <Table obj={object} setRequestData={setRequestData} />
              </tbody>
            );
          })}
        </table>
      </div>
    );
  };

export default Display;

然后你可以从你的Table组件触发它

import React, { useState } from "react";
import { Link } from "react-router-dom";
import axios from "axios";

const Table = props => {
  const removeData = () => {
    axios
      .delete("/students/" + props.obj.id)
      .then(() => {
        props.setRequestData(new Date());
      })
      .catch(err => console.log(err));
  };

  return (
    <React.Fragment>
      <tr>
        <td>{props.obj.name}</td>
        <td>{props.obj.birthday}</td>
        <td>{props.obj.address}</td>
        <td>{props.obj.zipcode}</td>
        <td>{props.obj.city}</td>
        <td>{props.obj.phone}</td>
        <td>{props.obj.email}</td>
        <td>
          <Link
            to={"/edit/" + props.obj.id}
            className="waves-effect waves-light btn"
          >
            Edit
          </Link>
        </td>
        <td>
          <button onClick={removeData} className="waves-effect red btn ">
            Remove
          </button>
        </td>
      </tr>
    </React.Fragment>
  );
};

export default Table;

不确定是否有帮助,但您始终可以从当前数组中删除该项目,因此不需要刷新,例如,您可以将接收 id 的函数作为 props 传递,然后过滤学生数组以排除与该元素匹配的元素id 然后用新的数组和计数属性更新状态,像这样

在你的父母中:

  const Display = () => {
   const [state, setState] = useState({ students: [], count: "" });

   const deleteItem = (id) => {
    const newStudents = state.students.filter(student => student.id !== id)
    const newCount = newStudents.length;
    setState({ students: newStudents, count: newCount })
   }
  // Rest of the code
  }

现在将该函数传递给您的子组件。

<Table obj={object} deleteItem={deleteItem} />

在子组件中,只需修改您的 removeData 方法以添加 deleteItem props:

  const Table = props => {
   const removeData = () => {
    axios
     .delete("/students/" + props.obj.id)
     .then(console.log("Deleted"))
     .catch(err => console.log(err));
    // Now if your request succeeds call the function to remove the item from the students state array
   props.deleteItem(props.obj.id);

   };
 // Rest of the code
 }

我知道这不能回答您的问题,但是当您使用 react 时,或者最好在应用程序端进行此计算和过滤器,就像在这种情况下,即使记录已从数据库中删除,我们也删除了记录来自学生状态对象,无需刷新页面。

请记住,您正在创建一个单页面应用程序,因此我们希望为用户提供最佳体验,而无需为用户执行的每个操作刷新页面。