【发布时间】: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 文档。
而且我不知道如何将声音对象与 /stop-sound 一起使用。
另一个例子
/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