django 如何同步消除两种成分

nlejzf6q  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(126)

假设我有两个组件,它们显示一个公共组件,当我向其中一个组件内的API发出删除请求时,另一个组件不会被删除,直到我刷新浏览器,我如何解决这个问题,以便同时消除公共组件
以下是组件:

import React, { useEffect, useState } from "react";
import { getTasks } from "../api/task.api";
import { TaskCard } from "./TaskCard";

export function TaskLists() {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    async function loadTasks() {
      const res = await getTasks();
      console.log(res.data);
      setTasks(res.data);
    }
    loadTasks();
  }, []);

  const removeTask = (id) => {
    setTasks(tasks.filter((task) => task.id !== id));
  };

  return (
    <div>
      {tasks.map((task) => (
        <TaskCard key={task.id} task={task} onDelete={removeTask} />
      ))}
    </div>
  );
}

字符串

import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

import { getTasks } from "../api/task.api";
import { TaskCard } from "./TaskCard";

export function Daycard({ hashv }) {
  let b = 0;
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    async function loadTasks() {
      const res = await getTasks();
      console.log(res.data);
      setTasks(res.data);
    }
    loadTasks();
  }, []);

  const removeTask = (id) => {
    setTasks(tasks.filter((task) => task.id !== id));
  };

  const [hash, setHash] = useState(hashv);
  const navigate = useNavigate();
  const handleClick = () => {
    if (b === 0) {
      navigate(`/tasks-create?hash=${hash}`);
      console.log(`the hash is ${hash}`);
    }
  };

  return (
    <div
      onClick={handleClick}
      className="col pb-5 bg-light border border-dark flex-grow-1"
      style={{ height: "auto" }}
    >
      {tasks.map((task) => {
        if (task.hash == hash) {
          b = 1;
          return <TaskCard key={task.id} task={task} onDelete={removeTask} />;
        }
      })}
    </div>
  );
}


卡内按删除的行为:


的数据


7gyucuyw

7gyucuyw1#

你可以使用redux或context。
或者在保存任务数组的主组件(包括这两个组件)中创建状态,并在这些组件中使用状态作为 prop 。
当您按下删除按钮时,请在主组件中运行删除功能。
你就会得到你想要的结果。

const MainComponent = () => {
    const [tasks, setTasks] = useState([]);
    return (
        <>
            ...
            <Daycard tasks={tasks} setTasks={setTasks} hashv={hashv}/>
            <TaskLists tasks={tasks} setTasks={setTasks}/>
            ...
        </>
    )
}

export function TaskLists({tasks, setTasks}) {
    
    //const [tasks, setTasks] = useState([]); => Remove this line
    ...
}

export function Daycard({ hashv, tasks, setTasks }) {
    let b = 0;
    // const [tasks, setTasks] = useState([]);  => Remove this line
    ...
}

字符串

相关问题