React 删除按钮后刷新页面

bab*_*830 2 reactjs use-effect

我的应用程序的删除功能工作正常,但是它要求用户在单击删除按钮后手动刷新页面才能查看数据库中的新元素列表。我想在点击事件后自动刷新。我在这个项目中使用反应钩子。然而,如果我删除,我找到了一个解决方案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;
Run Code Online (Sandbox Code Playgroud)

这是接收道具的第二个组件。

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;
Run Code Online (Sandbox Code Playgroud)

Nic*_*ick 8

钩子[]中的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;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)