【问题标题】:ReactJS DataCloneError: Failed to execute 'pushState' on 'History': MouseEvent object could not be clonedReactJS DataCloneError:无法在“历史”上执行“pushState”:无法克隆 Mou​​seEvent 对象
【发布时间】:2021-03-28 05:32:21
【问题描述】:

我正在尝试执行我的第一个 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 could not be cloned 我不知道如何修复它。

如果你能帮助我,我将非常感激。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    历史中存储的任何数据都需要序列化。对象、数组、字符串和数字可以序列化,但大多数其他对象,包括MouseEvent 对象不能。在这种情况下,您的 post 对象包含一个 MouseEvent 对象。

    在这种情况下,您甚至不想存储事件,因此您可以像这样修复您的代码:

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

    这样您就不会在封闭范围内隐藏post 变量,也不会用事件对象替换它。

    【讨论】:

      【解决方案2】:

      您所要做的就是删除/重命名匿名函数中的参数 帖子

      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

      您正在将渲染函数范围内的帖子从原始帖子重命名为 synteticEventHandler。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-07
        • 2020-10-22
        • 2015-02-17
        • 1970-01-01
        • 2015-02-19
        • 1970-01-01
        • 2018-03-06
        相关资源
        最近更新 更多