我正在使用es6映射构建显示数组中项目列表的应用。数组中的每个项目都包含文本和“删除”按钮,显然,“删除”按钮将根据特定ID从数组列表中删除项目。这是通过与和contextAPI连接的函数内部的reducer调度触发的。
这是我成功的基本语法...
import React, { useState, useContext} from "react";
//context
import { ListsContext } from "./listsContext";
function Lists() {
const { items, dispatch } = useContext(ListsContext);
return (
<div>
<h1>Lists</h1>
{items.length ? (
items.map(item => (
<div>
<ListTag
key={item.id}
item={item}
remove={() => dispatch({ type: "REMOVE", id: item.id });}
/>
</div>
))
) : (
<p> No Categories, Insert a category </p>
)}
</div>
);
}
function ListTag({ item, edit, confirm }) {
return (
<div className="list-tag">
<div className="list-info">
<p>{item.description}</p>
</div>
<div className="config-btn">
<button onClick={remove}>Remove</button>
</div>
</div>
);
}
export default Lists;
只需强调一下,上面的语法只会在单击“删除”按钮后立即从数组中删除项目。但是,我的目标是使模式弹出窗口模态化,并在单击“删除”按钮后单击“确认”以确认删除消息。 Modal confirmation #1 - codesandbox或Modal confirmation #2 by Chris Geirman - codesandbox查看更多Stackoverflow discussion。
不幸的是,带有链接的示例未使用react-hooks,reduce或contextAPI。因此,我独自尝试并取得了接近完美的结论。在从阵列中单击删除按钮后,Modal会弹出弹出窗口,并带有删除消息的确认信息,下方带有两个按钮(删除和取消)。不幸的是,它不会删除正确的项目,或者换句话说,是通过ID删除特定项目。例如,假设数组中有4个项目。如果我要删除位于数组顶部的第一个项目(“ Array One”),最终将删除位于底部的项目(“ Array Four”)。为了获得更好的见解,请查看codesandbox中的示例。
我正在努力寻找在弹出模式后按ID删除特定项目的解决方案。花几天时间,我什么都做不了。我需要帮助?我做错了什么?有解决方案,建议还是更好的建议?
当您考虑只需要从Lists
返回的one模态而不是在每个列表项上附加模态时,就可以轻松解决。单击列表项后,您可以添加选定的项以声明状态并在模式中使用它:
function Lists() {
const { items, dispatch } = useContext(ListsContext);
// Store the selected item instead
const [ selectedItem, setSelectedItem ] = useState();
const deleteItem = item => {
// Make sure your type and your reduce case label match
dispatch({ type: "REMOVE_CATEGORY", id: item.id });
setSelectedItem();
};
return (
<Fragment>
<div>
<h1>Lists</h1>
{items.length ? (
items.map(item => (
<div>
<ListTag
key={item.id}
item={item}
confirm={() => setSelectedItem(item)}
/>
</div>
))
) : (
<p> No Categories, Insert a category </p>
)}
</div>
// Confirm is now at the end of the list
// We pass in the selected item
<Confirm
item={selectedItem}
remove={deleteItem}
cancel={() => setSelectedItem(false)}
/>
</Fragment>
);
}
function ListTag({ item, edit, confirm }) {
return (
<div className="list-tag">
<div className="list-info">
<p>{item.description}</p>
</div>
<div className="config-btn">
<button onClick={confirm}>Remove</button>
</div>
</div>
);
}
function Confirm({ cancel, item, remove }) {
return (
<div>
{item && (
<Modal>
<p>
You are about to permanently delete <strong>{item.name}</strong>{" "}
category. Are you sure you want to do this?
</p>
<button onClick={() => remove(item)}>Remove</button>
<button onClick={cancel}>cancel</button>
</Modal>
)}
</div>
);
}