我正在尝试创建一个待办事项列表应用程序。基本功能包括添加和删除。因此,当用户选择一个或多个项目时,将出现一个删除按钮,该按钮将被删除。我的问题是,我正在实现一个切换状态,当用户单击todo项目时,它将是删除线(通过CSS添加删除线文本装饰(。当我添加两个项目时,问题就出现了。当我点击第一个项目时,它会被删除;当我删除它时,第一个项目会被删除,但第二个项目这次会被删除
codesandbox中正在运行的示例。只需尝试添加两个项目并删除第一个即可。第二个也得到了打击。
我相信这是因为切换状态值被记住了。
这是Content.js组件
import "./styles/content.css";
import Individual from "./Individual";
import { useEffect, useState } from "react";
import { updateItem, markIncomplete } from "./action/action";
const Contents = (props) => {
const items = useSelector((state) => state.todoReducer.items);
const dispatch = useDispatch();
const handleClick = (e, isComplete, content, id) => {
// console.log(isComplete);
if (isComplete === false) {
//evaluates false to true
const newobj = {
isComplete: true,
content,
id
};
dispatch(updateItem(newobj));
props.deletebutton(true);
} else {
const falseobj = {
isComplete: false,
content,
id
};
dispatch(markIncomplete(falseobj));
}
};
useEffect(() => {
console.log("statechanging of contents");
});
return (
<div className="content-ui">
<div>
{items.map((vals) => (
<Individual
vals={vals}
deletebutton={props.deletebutton}
handleClick={handleClick}
/>
))}
</div>
</div>
);
};
export default Contents;
这是处理切换功能的个性化.js
import { useDispatch, useSelector } from "react-redux";
import "./styles/content.css";
import { updateItem, markIncomplete } from "./action/action";
const Individual = (props) => {
console.log("child" + props.vals.isComplete);
const [toggle, isToggled] = useState(false);
const handleToggle = () => {
const mytoggle = !toggle;
isToggled(mytoggle);
};
return (
<div>
<div
className={toggle ? "toggled" : "card-elements"}
onMouseDown={handleToggle}
onClick={(e) => {
props.handleClick(
e,
props.vals.isComplete,
props.vals.content,
props.vals.id
);
handleToggle;
}}
>
{props.vals.content}
</div>
</div>
);
};
export default Individual;
触发器的Cs
.toggled {
/* border: 1px solid rgb(94, 94, 94); */
box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
text-align: left;
box-sizing: border-box;
padding: 10px 3px 10px 7px;
margin-top: 4px;
margin-bottom: 8px;
border-radius: 5px;
background-color: white;
font-size: 12px;
font-family: "Roboto ", monospace;
text-decoration: line-through;
}
.card-elements {
/* border: 1px solid rgb(94, 94, 94); */
box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
text-align: left;
box-sizing: border-box;
padding: 10px 3px 10px 7px;
margin-top: 4px;
margin-bottom: 8px;
border-radius: 5px;
background-color: white;
font-size: 12px;
font-family: "Roboto ", monospace;
}
您需要向映射的项添加键(控制台中也应该对此发出警告(。
键帮助React识别哪些项目已更改、添加或删除。
如React文件所述。
return (
<div className="content-ui">
<div>
{items.map((vals) => (
<Individual
key={vals.id} // <-- add unique key
vals={vals}
deletebutton={props.deletebutton}
handleClick={handleClick}
/>
))}
</div>
</div>
);