简体   繁体   中英

How to pass object with history.push in react-router v5?

How do I play a sound on the /start-sound and stop the sound on the /stop-sound?

/start-sound

const history = useHistory();

const startSound = () => {
  const sound = new Audio("test.mp3");
  sound.play();
  history.push("/stop-sound", [sound]);
}

/stop-sound

const stopSound = () => {
  sound.pause();
  sound.currentTime = 0;
}

This code will display an error in the browser.

DataCloneError: Failed to execute 'pushState' on 'History': An object could not be cloned.


history.push("/stop-sound", [sound]);

This style will follow the React Router documentation.

React Router | history

And I don't know how to use sound object with /stop-sound.


Another example

demo

/pass-text

const PassTextPage = () => {
  const history = useHistory();

  const passText= () => {
    history.push({
      pathname: "/view-text",
      state: { name: "Hello" }
    });
  };

  return <button onClick={passText}>pass</button>;
};

/view-text

const ViewTextPage = () => {
  const text = props.location.state.name; // 'props' is not defined.

  const viewText = () => {
    console.log(text);
  };

  return <button onClick={viewText}>view</button>;
};

App.jsx

const App = () => (
  <BrowserRouter>
    <Route exact path="/">
      <Home />
    </Route>
    <Route exact path="/pass-text">
      <PassTextPage />
    </Route>
    <Route exact path="/view-text">
      <ViewTextPage />
    </Route>
  </BrowserRouter>
);

The way you can pass property to navigated component

history.push({
pathname: '/stop-sound',
  state: { name: 'Hello'}
});

access like this in navigated component.

if its stateless component

let location = useLocation();

location.state.name

if class based component

 this.props.location.state.name

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