我在一个生产力工具网站上工作,用户可以添加任务并编辑或删除它,但我有一个错误,当你完成编辑后保存任务的按钮。经过一些调试,我意识到由于某种原因,“保存”按钮onCLick
正在调用handleSaveTask
函数,然后由于某种原因,handleEditTask
函数也被调用,这将isEditing
的状态设置回true,以便它保持在编辑模式。
有人知道这里发生了什么事我该怎么解决吗?下面是我的代码:
import React, { useState } from 'react';
import './TaskList.css'
interface taskList {
id: number;
name: string;
start: number;
end: number;
}
interface TaskListProps {
tasks: taskList[];
onChangeTask: Function;
onDeleteTask: Function;
}
interface TaskProps {
task: taskList;
onChange: Function;
onDelete: Function;
}
export const TaskList: React.FC <TaskListProps> = ({tasks, onChangeTask, onDeleteTask}) => {
return (
<div className='center'>
<h2 className='tasksTitle'>Tasks</h2>
<div className='taskTitle'>
<p className='taskTitle1'>Task Name</p>
<p className='taskTitle2'>Range</p>
</div>
{tasks.map((task) => (
<Task key={task.id} task={task} onChange={onChangeTask} onDelete={onDeleteTask} />
))}
</div>
);
}
const Task: React.FC <TaskProps> = ({task, onChange, onDelete}) => {
const [isEditing, setIsEditing] = useState(false);
let taskContent;
const handleEditTask = () => {
console.log("in Handle Edit Task");
setIsEditing(true);
}
const handleSaveTask = () => {
console.log("in Handle Save");
setIsEditing(false);
}
if (isEditing) {
taskContent = (
<div id='editTask'>
<input
value={task.name}
className="input inputName"
onChange={(e) => {
onChange({
...task,
name: e.target.value,
});
}}
/>
<input
value={task.start}
className="input inputNumber"
onChange={(e) => {
onChange({
...task,
start: e.target.value,
});
}}
/>
<input
value={task.end}
className="input inputNumber"
onChange={(e) => {
onChange({
...task,
end: e.target.value,
});
}}
/>
<button className="button buttonPrimary addButton" onClick={() => handleSaveTask()}>Save</button>
</div>
);
} else {
taskContent = (
<>
<div className='taskContent'>
<p className='taskContentItem1'>{task.name}</p>
<p className='taskContentItem2'>{task.start}-{task.end}</p>
<div className='taskContentItem3'>
<button className='button buttonPrimary' onClick={() => handleEditTask()}>Edit</button>
<button className="button buttonSecondary" onClick={() => onDelete(task.id)}>X</button>
</div>
</div>
</>
);
}
return (
<>
<div className='center' >
<label className='taskList'>
<div className='taskListItem1'>
{taskContent}
</div>
</label>
</div>
</>
);
}
Console output when pressing "Save" button
您也可以在这里观看现场演示:Demo
我尝试在依赖数组中添加一个带有isEditing
的useEffect钩子,但它导致了一个无限循环。
1条答案
按热度按时间x6h2sr281#
要修复此问题,请在
Task
的return
语句中删除 PackagetaskListItem1
div的<label>