更改数据时使用useEffect()进行更新的正确方法

时间:2020-04-28 02:23:04

标签: reactjs axios use-effect use-state use-context

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

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

我尝试过的

  • 使用[票证],但这只会导致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() }]);

  };

2 个答案:

答案 0 :(得分:1)

您需要注意tickets并返回它是否包含不会引起无限循环的数据:

useEffect(() => {
  if (tickets.length) return // so, we call just once
  getTickets();
  console.log("1", { tickets });
}, [tickets]);

答案 1 :(得分: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]);

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