javascript - react 类型错误 : Cannot read property 'type1' of undefined

标签 javascript reactjs typeerror

我在研究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 报告说没有这样的字段

enter image description here

类似的可执行codesandbox例子 example

最佳答案

解决方案:

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

说明:

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

onDragEnd Hook 的参数如下所示:

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

关于javascript - react 类型错误 : Cannot read property 'type1' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64135678/

相关文章:

Python:TypeError __init__() 正好需要 5 个参数(给定 4 个)

javascript - 使用 Django 中查询集的 Ajax 和 Jquery 填充选择框

javascript - 使用 localStorage 进行计数

javascript - 在 redux Action 创建者中设置监听器是一个坏主意吗?

javascript - Jest - 一个函数模拟多个测试文件的文件

python - discord.py 类型错误 : 'property' object is not iterable

javascript - 你如何优化网络音频应用程序中的垃圾收集以避免点击噪音?

javascript - 每次提交时,Rails 4 Ajax 在同一页面上多次渲染部分

reactjs - 循环组件中的钩子(Hook)

javascript - 为什么我得到 ".push not a function"?