简体   繁体   中英

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

I'm trying to do my first ReactApp and I got the DataCloneError error.

I have the following code:

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

and I want to trigger the method showPost when the button is clicked.

This is the showPost method:

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

I got this error DataCloneError: Failed to execute 'pushState' on 'History': MouseEvent object could not be cloned and I don't have any ideas how to fix it.

I would be very grateful if you culd help me out.

Any data stored in the history needs to be serialized. Objects, arrays, strings, and numbers can be serialized, but most other objects, including MouseEvent objects can't be. In this case, your post object contains a MouseEvent object.

In this case, you did not mean to even store the event, so you can fix your code like this:

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

That way you don't hide the post variable form the enclosing scope, and don't replace it with an event object.

All you have to do is to remove/rename argument inside anonymous function posts

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

As the docs says: https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers

You are renaming post in your render function scope from original post to synteticEventHandler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM