簡體   English   中英

ReactJS DataCloneError:無法在“歷史”上執行“pushState”:無法克隆 MouseEvent object

[英]ReactJS DataCloneError: Failed to execute 'pushState' on 'History': MouseEvent object could not be cloned

我正在嘗試做我的第一個 ReactApp,但我收到了 DataCloneError 錯誤。

我有以下代碼:

postsToShow.map((post, id)=>
   <ul key={id}>
        {post.title}
        <button onClick={(post)=>showPost(post)}>Show post</button>
    </ul>
    )

我想在單擊按鈕時觸發方法 showPost 。

這是 showPost 方法:

  const showPost=(post)=>
{
    history.push({
        pathname: '/showCurrentPost',
        state: {post: post}
    })}

我收到此錯誤 DataCloneError: Failed to execute 'pushState' on 'History': MouseEvent object 無法克隆,我不知道如何修復它。

如果您能幫助我,我將不勝感激。

存儲在歷史記錄中的任何數據都需要序列化。 對象、arrays、字符串和數字可以序列化,但大多數其他對象,包括MouseEvent對象不能。 在這種情況下,您的post object 包含MouseEvent object。

在這種情況下,您甚至不想存儲事件,因此您可以像這樣修復您的代碼:

<button onClick={(ev)=>showPost(post)}>Show post</button>

這樣您就不會隱藏封閉 scope 的post變量,也不會用事件 object 替換它。

您所要做的就是刪除/重命名匿名 function 帖子中的參數

ToShow.map((post, id)=>
   <ul key={id}>
        {post.title}
        <button onClick={(e)=>showPost(post)}>Show post</button>
    </ul>
    )

正如文檔所說: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

您正在將渲染 function scope 中的帖子從原始帖子重命名為 synteticEventHandler。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM