当我Router.push
重新加载页面时,我希望使用pushState。
在组件中使用以下代码:
import Router from "next/router";
//other code
const search = useCallback(
e => {
e.preventDefault();
Router.push(
`/products-search/${encodeURIComponent(
searchText
)}`,
`/products-search?q=${encodeURIComponent(
searchText
)}`
);
},
[searchText]
);
//other code
<form onSubmit={search}>
<input
type="text"
onChange={change}
value={searchText}
pattern=".{3,}"
title="3 characters minimum"
required
/>
<button type="submit">OK</button>
</form>
我的页面/products-search.js
ProductsSearch.getInitialProps = ({ query, store }) => {
//added try catch as next js may reload if there is an error
// running this on the client side
try {
const queryWithPage = withPage(query);
return {
query: queryWithPage
};
} catch (e) {
debugger;
}
};
答案 0 :(得分:9)
如果我的问题来了一些失落的灵魂,那是看不见的。
router.push(
'/organizations/[oid]/clients/[uid]',
`/organizations/${oid}/clients/${id}`
);
是我写的,它无需刷新即可导航。
router.push(
'/organizations/[oid]/clients/[cid]',// cid mistaken name but still worked. Should be uid
`/organizations/${oid}/clients/${id}`
);
错误的ID名称导致刷新,尽管它仍导航到正确的页面。 因此,请确保ID名称正确。
答案 1 :(得分:4)
当我将对象传递给Router.push
时,它可以正常工作:
const search = useCallback(
e => {
e.preventDefault();
Router.push({
pathname: "/products-search",
query: { q: searchText }
});
},
[searchText]
);
答案 2 :(得分:-1)
const search =()=> {
router.push(
/products-search/[searchText]
,
/products- search/${searchText}
,
{shallow:true}
);
}