【问题标题】:next js Router.push reloads page下一个 js Router.push 重新加载页面
【发布时间】:2020-01-14 13:42:55
【问题描述】:

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

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    万一有些迷失的灵魂带着我的问题来到这里,那是一种隐形。

    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 名称正确。

    【讨论】:

      【解决方案2】:

      当我将对象传递给 Router.push 时,它会按预期工作:

      const search = useCallback(
        e => {
          e.preventDefault();
          Router.push({
            pathname: "/products-search",
            query: { q: searchText }
          });
        },
        [searchText]
      );
      

      【讨论】:

        【解决方案3】:

        常量搜索 = () => { 路由器.push( /products-search/[searchText], /products- search/${searchText}, {浅:真} );

        }

        【讨论】:

          猜你喜欢
          • 2020-07-22
          • 2020-08-23
          • 2020-08-25
          • 2016-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多