[英]Programmatic access to history (history.push etc) in react-router v5 outside of components
[英]How to pass object with history.push in react-router v5?
如何在 /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 文檔。
而且我不知道如何將聲音對象與 /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>;
};
/查看文本
const ViewTextPage = () => {
const text = props.location.state.name; // 'props' is not defined.
const viewText = () => {
console.log(text);
};
return <button onClick={viewText}>view</button>;
};
應用程序.jsx
const App = () => (
<BrowserRouter>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/pass-text">
<PassTextPage />
</Route>
<Route exact path="/view-text">
<ViewTextPage />
</Route>
</BrowserRouter>
);
您可以將屬性傳遞給導航組件的方式
history.push({
pathname: '/stop-sound',
state: { name: 'Hello'}
});
在導航組件中像這樣訪問。
如果它的無狀態組件
let location = useLocation();
location.state.name
如果基於類的組件
this.props.location.state.name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.