首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >react TypeError:无法读取未定义的属性“”type1“”

react TypeError:无法读取未定义的属性“”type1“”
EN

Stack Overflow用户
提问于 2020-09-30 18:30:54
回答 1查看 53关注 0票数 3

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

代码语言:javascript
复制
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

所以他们是有联系的

代码语言:javascript
复制
import initialData from './initial-data'

所以它是以状态赋值的

代码语言:javascript
复制
state = initialData

这就是它的用法,以及我所描述的一切工作原理,这是示例中的代码

代码语言:javascript
复制
const start = this.state.columns[source.droppableId]
const finish = this.state.columns[destination.droppableId]

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

现在我想在下面添加我的条件,但它抛出了一个错误

代码语言:javascript
复制
    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

EN

回答 1

Stack Overflow用户

发布于 2020-10-01 22:05:20

解决方案:

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

用法:const typeDrag = this.state.tasks[draggableId]

解释:

在您的代码中,source没有draggableId属性。

所以typeDrag是未定义的,因为source.draggableId是未定义的。

您的onDragEnd钩子的参数如下所示:

代码语言:javascript
复制
{
  "draggableId": "task-2",
  "type": "TASK",
  "source": {
    "index": 1,
    "droppableId": "column-1"
  },
  "destination": {
    "droppableId": "column-2",
    "index": 0
  },
  "reason": "DROP"
}

通过检查您的沙箱示例,我看到您已经从方法参数(“draggableId”)中将result属性提取为常量:

代码语言:javascript
复制
const { destination, source, draggableId } = result; // line:28

因此,使用draggableId而不是source.draggableId可以解析TypeError: Cannot read property 'type1' of undefined

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64135678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档