0

下面的 useEffect 渲染、获取数据并显示一次(使用空数组作为 useEffect 中的第二个参数)。

每次用户将数据更改到数据库时(当用户使用 axios.post 时),我都需要它重新运行 useEffect。

我试过的

  • 使用 [tickets],但这只会导致 useEffect 无限运行
  • 也使用 [tickets.length] 和 [tickets, setTickets]
  • 尝试使用道具作为参数,但没有发现任何有用的东西

 

import React, { useState, createContext, useEffect } from "react";
import axios from "axios";

export const TicketContext = createContext();

export const TicketProvider = (props) => {
  console.log(props);
  const [tickets, setTickets] = useState([]);
  useEffect(() => {
    getTickets();
    console.log("1", { tickets });
  }, []);

  const getTickets = async () => {
    const response = await axios.get("http://localhost:4000/tickets/");
    setTickets(response.data);
  };
  return <TicketContext.Provider value={[tickets, setTickets]}>{props.children}
  </TicketContext.Provider>;
};
import React from "react";
import { useState, useEffect, useContext } from "react";
import Ticket from "../Ticket";
import { TicketContext } from "../contexts/TicketContext";

import AddBacklog from "../addData/AddBacklog";

const TicketDisplay = (props) => {
  const [tickets, setTickets] = useContext(TicketContext);

  return (
    <div className="display">
      <p>Antony Blyakher</p>
      <p>Number of Tickets: {tickets.length}</p>
      <div className="backlog">
        <h1>Backlog</h1>
        {tickets.map((currentTicket, i) => (
          <div className="ticketBlock">
            <Ticket ticket={currentTicket} key={i} />
          </div>
        ))}
      </div>
    </div>
  );
const AddBacklog = (props) => {
  const [tickets, setTickets] = useState("");

...

    axios.post("http://localhost:4000/tickets/add", newTicket).then((res) => console.log(res.data));

    setTickets((currentTickets) => [...currentTickets, { name: name, status: "backlog", id: uuid() }]);

  };
4

2 回答 2

1

tickets如果有数据不会导致无限循环,则需要注意并返回:

useEffect(() => {
  if (tickets.length) return // so, we call just once
  getTickets();
  console.log("1", { tickets });
}, [tickets]);
于 2020-04-28T02:31:10.443 回答
0
const fetchData = () => {
axios.get("http://localhost:7000/api/getData/").then((response) => {
  console.log(response.data);
  if (response.data.success) {
    SetIsLoading(false);
  }
  setDataSource(response.data.data);
});
};


useEffect(() => {
fetchData();
if (fetchData.length) fetchData();
}, [fetchData]);

通过这种方式,您可以在数据发生任何变化时实时获取数据。

于 2021-02-02T19:00:14.313 回答