【问题标题】:How to pass object with history.push in react-router v5?如何在 react-router v5 中通过 history.push 传递对象?
【发布时间】:2019-12-24 08:46:35
【问题描述】:

如何在 /start-sound 上播放声音并在 /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;
}

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

 DataCloneError: Failed to execute 'pushState' on 'History': 无法克隆对象。


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

这种风格将遵循 React Router 文档。

React Router | history

而且我不知道如何将声音对象与 /stop-sound 一起使用。


另一个例子

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

【问题讨论】:

  • 在 const ViewTextPage = (props) 中包含道具
  • 我收到错误“TypeError: Cannot read property 'location' of undefined”。
  • 发布viewTextPage组件的父组件
  • 为两个组件添加了父组件。
  • 改变你的父组件像这样

标签: javascript reactjs react-router


【解决方案1】:

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

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

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

如果它的无状态组件

let location = useLocation();

location.state.name

如果基于类的组件

 this.props.location.state.name

【讨论】:

  • 感谢您的回答。在 stop-sound.jsx 中写入“props.location.state.name”时,错误“'prop' is not defined”。被显示。你还有什么遗漏的吗?我在问题中添加了详细代码,所以如果您愿意,请再次回答。很抱歉这个基本问题。
猜你喜欢
  • 2018-02-20
  • 2020-08-29
  • 2020-11-05
  • 2019-10-19
  • 2017-05-18
  • 2021-08-26
相关资源
最近更新 更多