【问题标题】:react TypeError: Cannot read property 'type1' of undefined反应TypeError:无法读取未定义的属性'type1'
【发布时间】:2021-01-16 00:19:26
【问题描述】:

我正在研究react-beautiful-dnd示例,我想添加一个元素的条件排斥,但是我收到一个无法读取该字段的错误。 这个数据

const initialData = {
tasks: {
  'task-1': { id: 'task-1', content: 'Take out the garbage',type1: 'w' },
  'task-2': { id: 'task-2', content: 'Watch my favorite show',type1: 'a' },
  'task-3': { id: 'task-3', content: 'Charge my phone',type1: 'h' },
  'task-4': { id: 'task-4', content: 'Cook dinner',type1: 'w' }
},
columns: {
  'column-1': {
    id: 'column-1',
    title: 'To do',
    type2: 'all',
    taskIds: ['task-1', 'task-2', 'task-3', 'task-4']
  },
  'column-2': {
    id: 'column-2',
    title: 'In progress',
    type2: 'w',
    taskIds: []
  },
  'column-3': {
    id: 'column-3',
    title: 'Done',
    type2: 'a',
    taskIds: []
  }
},
// Facilitate reordering of the columns
columnOrder: ['column-1', 'column-2', 'column-3']  }export default initialData

所以他们是相连的

import initialData from './initial-data'

所以它是在状态中分配的

state = initialData

这就是它的使用方式,我描述的一切都有效,这是示例中的代码

const start = this.state.columns[source.droppableId]
const finish = this.state.columns[destination.droppableId]

if (start === finish) {
  const newTaskIds = Array.from(start.taskIds)

现在下面我想添加我的条件,它会引发错误

    const typeDrag = this.state.tasks[source.draggableId]
const typeDrop = this.state.columns[destination.droppableId]


if(typeDrag.type1!==typeDrop.type2)
{return}

我不明白为什么 start.taskIds 有效,但是 typeDrag.type1 报告说没有这样的字段

类似的可执行代码和框示例 example

【问题讨论】:

  • 为什么是.type1?您的任务对象不包含此字段。
  • 错误指出this.state.tasks 中没有属性[source.draggableId]。通过在调试器中捕获或登录控制台来检查 draggableId 是否正确
  • @VictorMolina 仔细看一切)
  • @AntonTemchenko 我加了个截图,可以看到id是存在的
  • DraggableLocation 没有属性draggableId: github.com/atlassian/react-beautiful-dnd/blob/master/docs/…

标签: javascript reactjs typeerror


【解决方案1】:

解决方案:

而不是:const typeDrag = this.state.tasks[source.draggableId]
使用:const typeDrag = this.state.tasks[draggableId]

解释:

在您的代码中 source 没有属性 draggableId
所以typeDrag 是未定义的,因为source.draggableId 是未定义的。

onDragEnd 钩子的参数如下所示:

{
  "draggableId": "task-2",
  "type": "TASK",
  "source": {
    "index": 1,
    "droppableId": "column-1"
  },
  "destination": {
    "droppableId": "column-2",
    "index": 0
  },
  "reason": "DROP"
}

通过检查您的沙盒示例,我发现您已经将 draggableId 属性从方法参数(“结果”)中提取为常量:

const { destination, source, draggableId } = result; // line:28

所以使用draggableId 而不是source.draggableId 会解析TypeError: Cannot read property 'type1' of undefined

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 2020-09-07
    • 2021-06-22
    • 2021-07-10
    • 2017-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多