【问题标题】:How can I create a popup message for users to confirm Yes/No when editing the column or deleting the rows from the table?在编辑列或从表中删除行时,如何为用户创建一个弹出消息以确认是/否?
【发布时间】:2021-06-05 11:48:58
【问题描述】:

前端代码:



function Home(props) {
  //make an axios request to get intents data from database
  const [intentsList, setintentsList] = useState([]);
  useEffect(() => {
    Axios.get("http://localhost:3001/intents").then((response) => {
      setintentsList(response.data);
    });
  }, []);

  const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
  //make an axios request to get information from database
  useEffect(() => {
    Axios.get("http://localhost:3001/customers").then((response) => {
      setCustomerList(response.data);
    });
  }, []);

  const updateCustomerContacted = (ID) => {
    confirm("Are you sure you want to edit?)
    Axios.put("http://localhost:3001/update", {
      contacted: newContacted,
      ID: ID,
    }).then((response) => {
      setCustomerList(
        customerList.map((val) => {
    alert("row updated!")
          const dateStr = new Date(val.latest_time_of_visit).toLocaleDateString(
            "en-CA"
          );
          const timeStr = new Date(
            val.latest_time_of_visit
          ).toLocaleTimeString();
          const dateTime = `${dateStr} ${timeStr}`;

          return val.ID == ID
            ? {
                ID: val.ID,
                name: val.name,
                email: val.email,
                counts_of_visit: val.counts_of_visit,
                latest_time_of_visit: dateTime,
                contacted: newContacted,
              }
            : val;
        })
      );
    });
  };

   const deleteCustomer = (ID) => {
    if (window.confirm("Are you sure to delete?"))
    Axios.delete(`http://localhost:3001/stats/delete/${ID}`).then(
      (response) => {
        alert("deleted");
        setCustomerList(
          customerList.filter((val) => {
            return val.ID != ID;
          })
        );
      }
    );
  };
  //pagination
  const [pageNumber, setPageNumber] = useState(0);
  const customersPerPage = 5; //change this number according to desired number of rows in a page
  const pagesVisited = pageNumber * customersPerPage;
  const displayCustomers = customerList
    .slice(pagesVisited, pagesVisited + customersPerPage)
    .map((val, key) => {
      const dateStr = new Date(val.latest_time_of_visit).toLocaleDateString(
        "en-CA"
      );
      const timeStr = new Date(val.latest_time_of_visit).toLocaleTimeString();
      const dateTime = `${dateStr} ${timeStr}`;
      return (
        <tr>
          <td>{val.ID}</td>
          <td>{val.name}</td>
          <td>{val.email}</td>
          <td>{val.counts_of_visit}</td>
          <td>{dateTime}</td>
          <td>{val.contacted}</td>
          <td>
            <select
              onChange={(event) => {
                setNewContacted(event.target.value);
              }}
            >
              <option value="" selected disabled hidden>
                Select Yes/No
              </option>
              <option value="Yes">Yes</option>
              <option value="No">No</option>
            </select>
            <button
              className="btn btn-primary"
              onClick={() => {
                updateCustomerContacted(val.ID);
              }}
            >
              Update
            </button>
          </td>
          <td>
            <button
              className="btn btn-danger"
              onClick={() => {
                deleteCustomer(val.ID);
              }}
            >
              Delete
            </button>
          </td>
        </tr>
      );
    });
  //to account for the fact that total number of customers cannot be divided equally among the pages
  const pageCount = Math.ceil(customerList.length / customersPerPage);
  //page change
  const changePage = ({ selected }) => {
    setPageNumber(selected);
  };

  //update contacted column
  const [newContacted, setNewContacted] = useState(0);

  {
    /*}
      const [currentTime, setCurrentTime] = useState(1);
    
      useEffect(() => {
        fetch("/time")
          .then((res) => res.json())
          .then((data) => {
            setCurrentTime(data.time);
          });
      }, []);
    */
  }

  //export to csv function

  const DataSet = [
    {
      columns: [
        {
          title: "S/N",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 100 },
        }, // width in pixels
        {
          title: "Customer Information",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
        {
          title: "Customer Email",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
        {
          title: "Counts of Visit",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 175 },
        }, // width in pixels
        {
          title: "Latest Time of Visit",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
        {
          title: "Contacted?",
          style: { font: { sz: "18", bold: true } },
          width: { wpx: 250 },
        }, // width in pixels
      ],
      data: customerList.map((val) => [
        { value: val.ID, style: { font: { sz: "14" } } },
        { value: val.name, style: { font: { sz: "14" } } },
        { value: val.email, style: { font: { sz: "14" } } },
        { value: val.counts_of_visit, style: { font: { sz: "14" } } },
        { value: val.latest_time_of_visit, style: { font: { sz: "14" } } },
        { value: val.contacted, style: { font: { sz: "14" } } },
      ]),
    },
  ];

  const useStyles = makeStyles(styles);
  const classes = useStyles;

  return (
    <div>
      <Navbar />
      <GridContainer>
        <GridItem xs={12} sm={6} md={6}>
          {" "}
          {/*width for different screen sizes*/}
          <Card>
            <CardHeader color="warning" stats icon>
              <CardIcon color="danger">
                <h4 className={classes.cardTitleWhite}>Product Statistics</h4>
                {/* <Icon>content_copy</Icon> */}
              </CardIcon>
              <p className={classes.cardCategory}>Used Space</p>
              <h3 className={classes.cardTitle}>
                49/50 <small>GB</small>
              </h3>
            </CardHeader>
            <CardBody>
              <BarChart />
            </CardBody>
            <CardFooter stats>
              <div className={classes.stats}>
                <Danger>
                  <Warning />
                </Danger>
                <a href="#pablo" onClick={(e) => e.preventDefault()}></a>
              </div>
            </CardFooter>
          </Card>
        </GridItem>
        <GridItem xs={12} sm={6} md={6}>
          <Card>
            <CardHeader color="dark" stats icon>
              <CardIcon color="dark">
                {/* <Store /> */}
                <h4 className={classes.cardTitleWhite}>Locations</h4>
              </CardIcon>

              <p className={classes.cardCategory}>Revenue</p>
              <h3 className={classes.cardTitle}>$34,245</h3>
            </CardHeader>
            <CardBody>
              <Map />
            </CardBody>
            <CardFooter stats>
              <div className={classes.stats}>
                <DateRange />
              </div>
            </CardFooter>
          </Card>
        </GridItem>
        {/* <GridItem xs={12} sm={6} md={6}>
                    <Card>
                        <CardHeader color="danger" stats icon>
                        <CardIcon color="danger">
                            <Icon>info_outline</Icon>
                        </CardIcon>
                        <p className={classes.cardCategory}>Fixed Issues</p>
                        <h3 className={classes.cardTitle}>75</h3>
                        </CardHeader>
                        <CardFooter stats>
                        <div className={classes.stats}>
                            <LocalOffer />
                            
                        </div>
                        </CardFooter>
                    </Card>
                    </GridItem>
                    <GridItem xs={12} sm={6} md={6}>
                    <Card>
                        <CardHeader color="info" stats icon>
                        <CardIcon color="info">
                            <Accessibility />
                        </CardIcon>
                        <p className={classes.cardCategory}>Followers</p>
                        <h3 className={classes.cardTitle}>+245</h3>
                        </CardHeader>
                        <CardFooter stats>
                        <div className={classes.stats}>
                            <Update />
                           
                        </div>
                        </CardFooter>
                    </Card>
                    </GridItem> */}
      </GridContainer>

      <GridContainer>
        <GridItem xs={12} sm={12} md={12}>
          <Card>
            <CardHeader color="warning">
              <h4 className={classes.cardTitleWhite}>Customer Information</h4>
              {/*}
              <p className={classes.cardCategoryWhite}>
                Visitors since 16th May, 2021
              </p>
                */}
            </CardHeader>
            <CardBody>
              <div className="dashboardcontainer">
                <div className="container"></div>
                <table className="customertable">
                  <thead>
                    <tr>
                      <th>S/n</th>
                      <th>Customer Name</th>
                      <th>Customer Email</th>
                      <th>Counts of Visit</th>
                      <th>Latest Time of Visit</th>
                      <th>Contacted?</th>
                      <th>Edit Contacted</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>{displayCustomers}</tbody>
                </table>
                <ReactPaginate
                  previousLabel={"Previous"}
                  nextLabel={"Next"}
                  pageCount={pageCount}
                  onPageChange={changePage}
                  containerClassName={"paginationBttns"}
                  pageLinkClassName={"paginationNumber"}
                  previousLinkClassName={"previousBttn"}
                  nextLinkClassName={"nextBttn"}
                  disabledClassName={"paginationDisabled"}
                  activeClassName={"paginationActive"}
                />
                <ExcelFile
                  filename="Customer Information"
                  element={
                    <button
                      type="button"
                      className="btn btn-success float-right m-3"
                    >
                      Export to CSV
                    </button>
                  }
                >
                  <ExcelSheet
                    dataSet={DataSet}
                    name="Customer Information Report"
                  ></ExcelSheet>
                </ExcelFile>
              </div>
              {/*}
              <Table
                tableHeaderColor="warning"
                tableHead={["ID", "Name", "Salary", "Country"]}
                tableData={[
                  ["1", "Dakota Rice", "$36,738", "Niger"],
                  ["2", "Minerva Hooper", "$23,789", "Curaçao"],
                  ["3", "Sage Rodriguez", "$56,142", "Netherlands"],
                  ["4", "Philip Chaney", "$38,735", "Korea, South"],
                ]}
              />
            */}
            </CardBody>
          </Card>
        </GridItem>
      </GridContainer>
    </div>
  );
}

export default Home;

后端代码:

//set up express server
const express = require("express");
const app = express();
//set up sql server
const mysql = require("mysql");
const cors = require("cors");

app.use(cors());
app.use(express.json());
//create a variable called db to make your SQL Statements
const db = mysql.createConnection({
  user: "",
  host: "",
  password: "",
  database: "",
});

//GET REQUEST to database to retrieve customers information from database
app.get("/customers", (req, res) => {
  db.query("SELECT * FROM customer_info", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

//Update customers
app.put("/update", (req, res) => {
  const ID = req.body.ID;
  const contacted = req.body.contacted;

  db.query(
    "UPDATE customer_info SET contacted = ? WHERE ID = ?",
    [contacted, ID],
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send(result);
      }
    }
  );
});

//Delete customers
app.delete("/stats/delete/:ID", (req, res) => {
  const ID = req.params.ID;

  db.query("DELETE FROM customer_info WHERE ID = ?", ID, (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

//api call to pull intents data
app.get("/intents", (req, res) => {
  db.query("SELECT * FROM data_analytics", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

//check if backend server is running
app.listen(3001, () => {
  console.log("Your server is running on port 3001");
});

参考上述前端和后端代码,如何更改我的代码,以便在编辑列或从表中删除行时,如何创建弹出消息供用户确认是/否?

所以我有这张表,它有更新和删除按钮,我如何向它添加确认消息供用户选择,以便他们有一个额外的确认层。如何通知用户行已被编辑或删除?

【问题讨论】:

  • 您是否使用任何库来呈现您的表格?
  • 我没有使用库,它是一个 html css 表
  • 您可以在问题中添加表格代码而不是后端吗?
  • 它在前端
  • 您可以在单击删除图标时打开一个对话框。您可以为此维持一种状态。

标签: javascript node.js reactjs frontend backend


【解决方案1】:

由于您在表格中使用 Material-UI,因此为了保持一致性,您可以使用 Material-UI-confirm 包来处理确认弹出窗口。你只需要用他们的ConfirmProvider 包装你的基础组件并使用他们的useConfirm 钩子来显示一个弹出消息。

另外,请考虑只保留问题中代码的必需部分,以便每个人都能更轻松地完成它。

【讨论】:

  • 我没有使用仅用于测试的 Material UI
  • 我明白了。在这种情况下,您可以只使用confirmwindow.confirm 方法。它是一种阻止方法,显示带有两个选项的特定于浏览器的弹出窗口 - “确定”和“取消”,并返回一个布尔值。您可以在 Axios 调用之前使用它。
  • 哦,所以只需在 axios 调用前端的 update 和 delete 方法后添加确认或 window.confim ?
  • 如果你想阻止更新/删除 Axios 调用,如果用户在弹出窗口中选择“NO”,那么你必须在调用之前放置它。通话结束后,您可以使用alertwindow.alert 通知用户该行是否已更新/删除。
  • 代码是window.alert("message")?像以前的 Axios。?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
  • 2022-08-24
  • 1970-01-01
相关资源
最近更新 更多