当我以自己的方式拖动项目时,我试图定义项目类型。但是,如果我这样做并拖动项目,就会出现问题,它会在删除项目后向我显示“不变违规:必须定义项目类型”。这意味着我有一个包含 ItemTypes 的文件,我在其中定义了所有内容:
export const ItemTypes = {
'CARD': "card",
'PHONE': "phone",
'WEAPON': "weapon",
'FOOD': "food",
'DRINK': "drink"
};
在主库存上,项目数组就像这样
const [items, setItems] = useState([
{
type: "PHONE",
label: "test",
itemname: "test",
pieces: 10,
itemweight: 0.2
},
{
type: "CARD",
label: "test5",
itemname: "test5",
pieces: 5,
itemweight: 0.2
}
]);
以及我定义被拖动的项目的项目组件:
const Item = props => {
const [{ isDragging }, drag] = useDrag({
item: {
type: ItemTypes[props.type],
index: props.index,
label: props.label,
itemname: props.name,
pieces: props.pieces,
weight: props.itemweight
},
collect: (monitor) => ({
isDragging: !!monitor.isDragging()
})
});
所以最后这意味着当我将项目放到目标容器上时,我收到错误“不变违规:必须定义项目类型”。
useDrag 最近发生了变化,请参阅: https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0
由于 DnD v14 API 更改,您需要将“type”键移出“item”键:
const Item = props => {
const [{ isDragging }, drag] = useDrag({
item: {
index: props.index,
label: props.label,
itemname: props.name,
pieces: props.pieces,
weight: props.itemweight
},
type: ItemTypes[props.type], //MOVE THIS OUTSIDE ITEM OBJECT
collect: (monitor) => ({
isDragging: !!monitor.isDragging()
})
});
TLDR:
有关此的文档:https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0
这应该适用于所有最新的 React 版本。作为参考,我使用:
"react": "^17.0.2",
"react-dnd": "^15.0.2",
"react-dnd-html5-backend": "^15.0.2",