![](/img/trans.png)
[英]Back button is not working when using history.pushState() in ReactJs
[英]How to trigger change when using the back button with history.pushstate and popstate?
當涉及到js時,我幾乎是一個新手,所以如果我遺漏了一些非常簡單的話,我很抱歉。
基本上,我已經做了一些使用history.pustate和popstate的研究,我已經做了,所以查詢字符串被添加到url的末尾( ?v=images
)或( ?v=profile
)... ( v
表示'view')使用此:
var url = "?v=profile"
var stateObj = { path: url };
history.pushState(stateObj, "page 2", url);
我想這樣做,所以我可以將內容加載到div但不重新加載我使用.load()
函數完成的頁面。
然后我使用了這段代碼:
$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
在$(document).ready()
部分,稍后在<script>
標簽內嘗試,但都沒有工作。
我不知道如何制作它,所以當我使用后退按鈕時內容會發生變化,或者至少這樣做,所以我可以觸發自己的功能這樣做; 我假設它與狀態對象有關?! 我似乎無法在網上找到任何清楚解釋過程的內容。
如果有人可以幫助我,這將是驚人的,並提前感謝任何人!
popstate
僅在有一個狀態時包含狀態。
當它像這樣:
pushState
添加狀態 然后沒有狀態,因為初始頁面是定期加載的,而不是pushState
。 因此, onpopstate
事件以null
state
觸發。 因此,當它為null
,表示應加載原始頁面。
您可以實現它,以便一致地調用history.pushState
,您只需要提供這樣的狀態更改函數: 單擊此處查看jsFiddle鏈接
function change(state) {
if(state === null) { // initial page
$("div").text("Original");
} else { // page added with pushState
$("div").text(state.url);
}
}
$(window).on("popstate", function(e) {
change(e.originalEvent.state);
});
$("a").click(function(e) {
e.preventDefault();
history.pushState({ url: "/page2" }, "/page2", "page 2");
});
(function(original) { // overwrite history.pushState so that it also calls
// the change function when called
history.pushState = function(state) {
change(state);
return original.apply(this, arguments);
};
})(history.pushState);
也許這不是最佳解決方案,也許它不適合您的需求。 但對我來說,最好重新加載頁面。 因此頁面是一致的,它根據當前的查詢字符串加載所有內容。
$(document).ready(function() {
$(window).on("popstate", function (e) {
location.reload();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.