【问题标题】:Cannot read property 'cards' of undefined in @lourenci/react-kanban when adding a card添加卡片时无法读取@lourenci/react-kanban 中未定义的属性“卡片”
【发布时间】:2021-01-09 06:21:18
【问题描述】:

在将react-kanban 用于我的项目之前,我正在对其进行测试。我在codesandbox.io 创建了这段代码。

  import React,{useEffect , useState} from 'react'
  import Board, { addCard } from '@lourenci/react-kanban'
  import '@lourenci/react-kanban/dist/styles.css'

  export default function Index() {

    const [board, setBoard] = useState({
      columns: [
        {
          id: 1,
          title: 'Backlog',
          cards: [
            {
              id: 1,
              title: 'Add card',
              description: 'Add capability to add a card in a column'
            },
          ]
        },
        {
          id: 2,
          title: 'Doing',
          cards: [
            {
              id: 2,
              title: 'Drag-n-drop support',
              description: 'Move a card between the columns'
            },
          ]
        }
      ]
    }
    )
    const addcard =(e)=>{
      const newBoard = addCard(board,1,{
        id: 3,
        title: "dfdfdfdff",
        description: "SDfsfsf"
      })
      setBoard(newBoard)
    }

      useEffect(() => {
        console.log("fetch packages")
      }, [])
    
      return (
        <div>
          <button onClick={addcard} >Add Card</button>
          <Board>{board}</Board>
        </div>
      )
  }

挑战是我正在使用他们的助手将卡片添加到板上的列中,但它返回错误。我做错了什么?还是一个错误?

TypeError
Cannot read property 'cards' of undefined

提前感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs use-state


    【解决方案1】:

    我已经浏览了documentation,不幸的是没有足够的例子来说明如何使用addCard。如果您看到下图,addCard 的第二个参数是inColumn,但他们没有提到输入是什么,无论是 id 列还是其他列。所以我尝试调试并发现inColumnObjectid

     const addcard = (e) => {
        const newBoard = addCard(board, { id: 1 } <-- this is the input of column, { 
          id: 2,
          title: "dfdfdfdff",
          description: "SDfsfsf"
        });
        setBoard({...newBoard});
      };
    

    注意:据我所知,您需要手动处理每张卡的ids。否则,您会在控制台中看到警告。

    我已经更新了你的例子,它正在工作

    【讨论】:

    • 很好,也很有趣,因为他们的其他文档暗示addCard 与受控板不兼容。不错的作品。我还发现他们的 API 文档水平相当差。我将把我的答案作为手动更新棋盘数据的示例。
    【解决方案2】:

    您有一个受控板,因此根据他们的props API 文档,addCard 无效。

    编辑:正如@Naren 回答的那样,addCard 实用程序确实确实有效。我将我的答案作为手动更新传递给Board 组件的数据的示例,它们只是“镜像”。

    您需要自己管理棋盘数据。这是addcard 处理程序的示例:

    const addcard = (e) => {
      setBoard(board => ({
        ...board,
        columns: board.columns.map(column => column.id === 1 ? {
          ...column,
          cards: [...column.cards, {
            id: 3,
            title: "dfdfdfdff",
            description: "SDfsfsf"
          }]
        } : column)
      }));
    };
    

    【讨论】:

      猜你喜欢
      • 2022-06-19
      • 2020-01-08
      • 2021-12-04
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多