如何在react-router v5中传递带有history.push的对象?

时间:2019-12-24 08:46:35

标签: javascript reactjs react-router

如何在/ start-sound上播放声音并停止/ stop-sound上的声音?

/开始声音

const history = useHistory();

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

/停止声音

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

此代码将在浏览器中显示错误。

  

DataCloneError:无法在“历史记录”上执行“ pushState”:无法克隆对象。


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

此样式将遵循React Router文档。

React Router | history

我不知道如何在/ stop-sound中使用声音对象。


另一个例子

demo

/密码

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

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

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

/查看文字

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>
);

1 个答案:

答案 0 :(得分:1)

将属性传递给导航组件的方式

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

在导航组件中像这样访问。

如果它是无状态组件

let location = useLocation();

location.state.name

如果是基于类的组件

 this.props.location.state.name