【資料圖】
本教程操作環境:Windows10系統、react18.0.0版、Dell G3電腦。
react頁面傳值刷新后值消失怎么辦?
解決react路由跳轉傳參刷新頁面后參數丟失問題
import { useHistory } from "react-router-dom";const history = useHistory(); history.push({ pathname: "/details", state: { name: name, id: id, },});
在history中使用state確實可以傳參數,在進入頁面時可以正常顯示,但是在刷新頁面后state里面的數據會清空,頁面就無法正常顯示。
import { useHistory } from "react-router-dom";const history = useHistory(); history.push({ pathname: "/details", query: { name: name, id: id, },});
使用query是在跳轉鏈接中增加參數,可以在實現傳參的同時刷新頁面后數據不會丟失,但是如果傳的參數過多鏈接會很長。
import { useLocation } from "react-router-dom";const location = useLocation();const name = location.query.name;const id = location.query.id;// 獲取state參數的寫法const name = location.state.name;const id = location.state.id;
這是在跳轉頁面獲取參數的方式
(親測有效,但是會有類型報錯)
推薦學習:《react視頻教程》
以上就是react頁面傳值刷新后值消失怎么辦的詳細內容,更多請關注php中文網其它相關文章!
關鍵詞: React