2

On the following very basic project:

https://stackblitz.com/edit/react-history-push-with-function-as-arg?file=src%2Fpages%2FPage1.jsx

I have the following code:

import React from "react";

class Page1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      letter: 'A',
    };
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.history.push({
      pathname: '/page2',
      state: {
        myFunction: () => {
          console.log('Cancelling Axios Request!');
        },
      }
    });
    return false;
  };

  render() {
    return <>
      <form onSubmit={this.handleSubmit}>
        <div>You are currently on: Page 1 (Letter: {this.state.letter})</div>
        <br />
        <button type="submit">SUBMIT</button><br />
      </form>
    </>;
  }
}

export default Page1;

My problem is that I need to pass a function to the Page2 through the call to: this.props.history.push({...}). For that I'm using: myFunction inside the state array (which is normally used to send parameters on the transition).

Side note you can skip: in my real scenario will be a function that will take care of cancelling an Axios call, especifically with: axios.canceltoken.source().cancel(). Reference: https://www.pluralsight.com/guides/all-need-to-know-about-axios),

but when transitioning to Page2 I get the following error:

Error: Failed to execute 'pushState' on 'History': () => {
console.log('hello world');
} could not be cloned.

as you can see here:

enter image description here

I know I could save the function on the window object while on Page1 and use it while on Page2 but I think that's not a good practice. As I said above, my end goal is to be able on Page2 to cancel an Axios request I started on Page1.

Is there a way for me to pass that function to Page2?

Thanks in advance!

4

0 回答 0