下一个JS Router.push重新加载页面

时间:2020-01-14 13:42:55

标签: reactjs next.js

当我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;
  }
};

3 个答案:

答案 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} );

}