删除按钮后反应刷新页面 [英] React refresh the page after delete button

查看:41
本文介绍了删除按钮后反应刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

 import React, { useState, useEffect } from "react";从axios"导入 axios;从../Table/Table"导入表;导入./Display.css";const 显示 = () =>{const [state, setState] = useState({学生: [], 计数: "" });const [searchItem, setsearchItem] = useState({物品: ""});const 搜索 = e =>{setsearchItem({ item: e.target.value });};useEffect(() => {公理.get("/学生").then(响应 => {设置状态({学生: response.data.students,计数: response.data.count});}).catch(函数(错误){控制台日志(错误);});}, []);//如果我删除这个方括号,它就可以工作const nameFilter = state.students.filter(list => {返回 list.name.toLowerCase().includes(searchItem.item.toLowerCase());});返回 (<div><h3 align="center">学生表</h3><p align="center">学生总数:{state.count}</p><div className="input-body"><div className="row"><div className="input-field col s6"><input placeholder="search student" onChange={Search}/>

<table className="table table-striped"><头><tr><th>姓名</th><th>出生日期</th><th>地址</th><th>邮政编码</th><第>城市</th><th>电话</th><th>电子邮件</th><th colSpan="2">Action</th></tr></thead>{nameFilter.map((object, index) => {返回 (<tbody key={index}><表 obj={object}/>//在这里我将道具传递给另一个组件.</tbody>);})}

);};导出默认显示;

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

import React, { useState } from "react";从react-router-dom"导入{链接};从axios"导入 axios;const 表 = 道具 =>{const removeData = () =>{公理.delete("/students/" + props.obj.id).then(console.log("已删除")).catch(err => console.log(err));};返回 (<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><链接to={"/edit/" + props.obj.id}className="waves-effect wave-light btn">编辑</链接></td><td><button onClick={removeData} className="waves-effect red btn ">消除</td></tr></React.Fragment>);};导出默认表;

解决方案

useEffect 钩子中的 [] 是一个依赖数组,用于触发效果运行.如果您想触发效果(而不是无情地关闭),您可以创建一个新变量来触发该效果运行.

import React, { useState, useEffect } from "react";从axios"导入 axios;从../Table/Table"导入表;导入./Display.css";const 显示 = () =>{const [state, setState] = useState({学生: [], 计数: "" });const [requestData, setRequestData] = useState(new Date());const [searchItem, setsearchItem] = useState({物品: ""});const 搜索 = e =>{setsearchItem({ item: e.target.value });};useEffect(() => {公理.get("/学生").then(响应 => {设置状态({学生: response.data.students,计数: response.data.count});}).catch(函数(错误){控制台日志(错误);});}, [请求数据]);const nameFilter = state.students.filter(list => {返回 list.name.toLowerCase().includes(searchItem.item.toLowerCase());});返回 (<div><h3 align="center">学生表</h3><p align="center">学生总数:{state.count}</p><div className="input-body"><div className="row"><div className="input-field col s6"><input placeholder="search student" onChange={Search}/>

<table className="table table-striped"><头><tr><th>姓名</th><th>出生日期</th><th>地址</th><th>邮政编码</th>第<第>个城市个<th>电话</th><th>电子邮件</th><th colSpan="2">Action</th></tr></thead>{nameFilter.map((object, index) => {返回 (<tbody key={index}><表 obj={object} setRequestData={setRequestData}/></tbody>);})}

);};导出默认显示;

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

import React, { useState } from "react";从react-router-dom"导入{链接};从axios"导入 axios;const 表 = 道具 =>{const removeData = () =>{公理.delete("/students/" + props.obj.id).then(() => {props.setRequestData(new Date());}).catch(err => console.log(err));};返回 (<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><链接to={"/edit/" + props.obj.id}className="waves-effect wave-light btn">编辑</链接></td><td><button onClick={removeData} className="waves-effect red btn ">消除</td></tr></React.Fragment>);};导出默认表;

The delete function of my app is working fine, however it requires the user to manually refresh the page after the user click the delete button in order to see the new list of elements in my database. I would like to automatically refresh after the click event. I am using react hooks for this projects. However, I found one solution if I remove useEffect's [] but in my backend it shows, its requesting crazily. I don't know, is it wise to remove useffect's [ ]?

Here is the component where it fetches data from backend and passes the props to another component

 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;

This is second component which receives the 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;

解决方案

The [] in the useEffect hook is a dependency array to trigger the effect to run. If you want to trigger the effect (without it going off mercilessly), you can create a new variable that triggers that effect to run.

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;

Then you can trigger it from your Table component:

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;

这篇关于删除按钮后反应刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆