我有一个显示搜索结果的路径/discovery
,我还尝试将搜索状态与url查询参数同步,因此如果用户键入“chicken”,url将变为-/discovery?query=chicken&page=1
用户点击结果后,将导航至/mealpreview/[id]
然而,当我尝试像这样往回导航时:
<IconButton color="inherit" onClick={() => router.back()}>
<ArrowBackIcon />
</IconButton>
URL变回-/discovery?query=chicken&page=1
,但是它仍然呈现相同的页面。
当我再次点击返回按钮时,它工作并返回到/discovery
当我不使用url参数时一切正常,这里发生了什么?
顺便说一下,这是我如何同步我的网址状态:
import React, { Component } from "react";
import qs from "qs";
const updateAfter = 700;
export const isClient = !(typeof window === "undefined");
const searchStateToURL = (searchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : "";
const withURLSync = (TestSearch) =>
class WithURLSync extends Component {
state = {
searchState: qs.parse(isClient && window.location.search.slice(1)),
};
componentDidMount() {
if (isClient) {
window.addEventListener("popstate", this.onPopState);
}
}
componentWillUnmount() {
clearTimeout(this.debouncedSetState);
window.removeEventListener("popstate", this.onPopState);
}
onPopState = ({ state }) =>
this.setState({
searchState: state || {},
});
onSearchStateChange = (searchState) => {
clearTimeout(this.debouncedSetState);
this.debouncedSetState = setTimeout(() => {
window.history.pushState(
searchState,
null,
searchStateToURL(searchState)
);
}, updateAfter);
this.setState({ searchState });
};
render() {
const { searchState } = this.state;
return (
<TestSearch
{...this.props}
searchState={searchState}
onSearchStateChange={this.onSearchStateChange}
createURL={searchStateToURL}
/>
);
}
};
export default withURLSync;
1条答案
按热度按时间6yt4nkrj1#
请使用NextJs
router.push
或router.replace
,而不要使用window.history.pushState
。