无法获取“id”,即使它在其他功能中运行良好且一切正常

问题描述 投票:0回答:1

所以我写了这个函数,它调用不同文件中的函数,使用 React JS 中的 Context

我只在这个函数中收到此错误,就像在其他类似的函数中一样,它工作得很好

代码 索引.js

import { useContext } from "react";
import { PlaygroundContext } from "../../../Providers/PlaygroundProvider";
import { ModalContext, modalConstants } from "../../../Providers/ModalProvider";
import { Modal } from "../../../Providers/Modals/Modal.js";

const Folder = ({folderTitle, cards, id, file}) =>{

    const {deleteFolder, deleteFile} =useContext(PlaygroundContext);
    const {openModal} = useContext(ModalContext)
    const {folders} = useContext(PlaygroundContext)
    const navigate = useNavigate();

 
    const onDeleteFile = () => {
        deleteFile(id, file.id);
    }

     return(  
                        <div><span class="material-symbols-outlined" onClick={onDeleteFile}>delete</span>
                        {/* <span class="material-symbols-outlined">edit</span> */}
                        </div>


)             

这就是功能

    const deletefile = (fileId, id) => {
        console.log(id, fileId);
        const copiedFolders = [...folders]
        for(let i=0 ; i < copiedFolders.length; i++){
            if(copiedFolders[i].id === id){
                const files = [...copiedFolders[i].files];
                copiedFolders[i].files = files.filter((file) => {
                    return file.id !== fileId;
                })
                break;
            }
        }
        localStorage.setItem('data', JSON.stringify(copiedFolders));
        setFolders(copiedFolders);
    }

后来我把它正确地传递到索引文件中

错误是

Cannot read properties of undefined (reading 'id')
TypeError: Cannot read properties of undefined (reading 'id')
    at onDeleteFile (http://localhost:3000/main.a4ed982a4138ab8e8eb8.hot-update.js:72:25)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:34521:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:34565:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:34622:35)
    at invokeGuardedCallbackAndCatchFirstError (http://localhost:3000/static/js/bundle.js:34636:29)
    at executeDispatch (http://localhost:3000/static/js/bundle.js:38779:7)
    at processDispatchQueueItemsInOrder (http://localhost:3000/static/js/bundle.js:38805:11)
    at processDispatchQueue (http://localhost:3000/static/js/bundle.js:38816:9)
    at dispatchEventsForPlugins (http://localhost:3000/static/js/bundle.js:38825:7)
    at http://localhost:3000/static/js/bundle.js:38985:16

我尝试使用各种方法进行调试,但它们根本不起作用......

reactjs function
1个回答
0
投票

您在执行之前尝试过记录文件吗?

const onDeleteFile = () => {
   console.log({file, id: file.id})
   // deleteFile(id, file.id)
}
© www.soinside.com 2019 - 2024. All rights reserved.