我有两个兄弟组件,即<AddTask/>
和<TaskList/>
,它们是<Home/>
组件的子组件。目前,当我在我的ToDo应用程序中添加一个新任务时,它将被添加,但我需要刷新页面才能显示新任务。在<AddTask/>
组件中单击Add
按钮后,如何立即刷新<TaskList/>
组件?
这是我的<AddTask/>
组件
const AddTask = () => {
const [task, setTask] = useState("");
const [isPending, setIsPending] = useState(false);
const handleClick = (e)=> {
e.preventDefault();
setIsPending(true);
const todo = {task};
fetch('http://localhost:8000/tasks', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(todo)
})
.then(()=>{
setIsPending(false);
})
};
return (
<form className="new-task" onSubmit={handleClick}>
<input className="input"
type="text"
required
value={task}
onChange= { (e)=> setTask(e.target.value) }
/>
<button className="add-task">Add</button>
</form>
);
}
export default AddTask;
这是<Home/>
组件
import TaskList from "./TaskList";
import useFetch from "./useFetch";
const Home = () => {
const { data: task, isPending, error} = useFetch('http://localhost:8000/tasks');
return (
<div className="home">
<AddTask />
{ error && <div>Failed to fetch data.</div> }
{ isPending && <div>Loading...</div> }
{ task && <TaskList task={task} /> }
</div>
);
}
export default Home;
在Home
组件中,您需要tasks
状态,以便您可以在AddTask
组件中更新该状态
import TaskList from "./TaskList";
import useFetch from "./useFetch";
import { useState, useEffect } from 'react'
const Home = () => {
const [tasks, setTasks] = useState(null);
const { data: task, isPending, error} = useFetch('http://localhost:8000/tasks');
useEffect(() => {
if (task) setTasks(task)
}, [task])
return (
<div className="home">
<AddTask setTasks={setTasks} />
{ error && <div>Failed to fetch data.</div> }
{ isPending && <div>Loading...</div> }
{ tasks && <TaskList task={tasks} /> }
</div>
);
}
export default Home;
AddTask
const AddTask = ({ setTasks }) => {
const [task, setTask] = useState("");
const [isPending, setIsPending] = useState(false);
const handleClick = (e)=> {
e.preventDefault();
setIsPending(true);
const todo = {task};
fetch('http://localhost:8000/tasks', {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(todo)
})
.then(()=>{
setIsPending(false);
setTasks(prev => ([...prev, task]))
})
};
return (
<form className="new-task" onSubmit={handleClick}>
<input className="input"
type="text"
required
value={task}
onChange= { (e)=> setTask(e.target.value) }
/>
<button className="add-task">Add</button>
</form>
);
}
export default AddTask;