【问题标题】:Problems with Item Types in react dnd (Invariant Violation: item type must be defined)react dnd中的项目类型问题(不变违规:必须定义项目类型)
【发布时间】:2020-10-01 16:49:46
【问题描述】:

当我以自己的方式拖动项目时,我正在尝试定义项目类型。但是如果我这样做并拖动项目,就会出现问题,它会在删除项目后显示“不变违规:必须定义项目类型”。这意味着我有一个包含 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()
      })
    });

所以最后这意味着当我将项目放在目标容器上时,我收到错误“不变违规:必须定义项目类型”。

【问题讨论】:

  • item 对象中的type 属性意外未定义时,我遇到了类似的问题。你的 props 对象设置正确吗?

标签: javascript reactjs react-dnd


【解决方案1】:

最近对 useDrag 进行了更改,请参阅: https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0

【讨论】:

    【解决方案2】:

    由于 DnD v14 API 更改,您需要将“类型”键从“项目”键中移出:

    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",
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 2014-02-19
      • 2014-03-17
      • 2013-06-19
      • 1970-01-01
      • 2019-12-28
      • 2021-09-11
      • 2017-03-29
      相关资源
      最近更新 更多