【问题标题】:Losing query string by refreshing page in Nextjs using express通过使用 express 在 Nextjs 中刷新页面丢失查询字符串
【发布时间】:2020-03-11 20:15:41
【问题描述】:

我在使用 nextjs 时遇到了问题,但没有一个解决方案能帮到我!!!我,我试图在我的 SSR 项目中使用动态路由,在 localhost 中一切正常,但是当我尝试将其上传到服务器或我的 IIS 问题显示在 :问题在于,在第一次从服务器渲染时一切正常,刷新页面后,我丢失了查询字符串并且发生了未定义的错误。这是我的代码:

Server.js:

const express = require("express");
const next = require("next");
const port = process.env.PORT || 3003;

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("/", (req, res) => {
    return app.render(req, res, "/index");
  });

  server.get("/test?org&des&roomRules&departing&returning", (req, res) => {
    return app.render(req, res, "/test" , {
      org: req.query.org ,
      des: req.query.des,
      roomRules:req.query.roomRules,
      departing: req.query.departing,
      returning: req.query.returning,
    });
  });

  server.get("*", (req, res) => {
    return handle(req, res);
  });
  server.listen(port, err => {
    if (err) throw err;
    console.log(`READY ON  http://localhost:${port}`);
  });
});

父组件:

const RoundButton = props => {
  const { searchParams , name} = props;
  const URL2 = `/test?org=${searchParams.org}&des=${searchParams.des}&roomRules=${searchParams.roomRules}&departing=${searchParams.orgDate}&returning=${searchParams.desDate}`;
  return (
    <Link  href={URL2} as={URL2}>
      Test
    </Link>
  );
};

测试组件:

function Test(props) {
  return (
    <div>
      <h1>Test</h1>
      <h2>roomrules :{props.queryStrings}</h2>
    </div>
  )
}

Test.getInitialProps =  ({query}) => {
  const queryStrings =  query;
  return {
     queryStrings: queryStrings 
  };    
};

export default Test

如你所见,我使用了 getInitialProps,它只适用于第一次渲染。

最后是我在 package.json 中的脚本:

"scripts": {
  "dev": "node server.js",
  "build": "next build && next export",
  "start": " node server.js"
},

要发布,我在 cmd 中编写“npm run build”。有什么解决办法吗?

【问题讨论】:

  • 您找到解决方案了吗?

标签: node.js reactjs server-side-rendering


【解决方案1】:

在使用下一个 js 时,可以使用以下方法使 URL 参数在刷新时保持不变: 假设您有一个名为 TestComponent 的组件:

TestComponent.getInitialProps = async (context: any) => {
  const { oid } = context.query;
  return { id: oid };
};

oid是页面刷新后要持久化的参数,不能为undefined。

export default function TestComponent(props: any) {
     props.id
}

这是您在源代码中使用的方法,另一种方法如下:

export default function TestComponent(props: any){
  const router = useRouter();
  const { oid } = router.query;
}

现在您可以访问 oid 并且对于 useEffect 函数,请使用以下方法:

export default function TestComponent(props: any){
      const router = useRouter();
      const { oid } = router.query;
      useEffect(function(){
       }, [oid])
    }

使用此设置,您的代码也应该在 Refresh 上工作,考虑是否有多个调用从服务器获取数据,您必须精确检查多个请求。

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 2011-07-18
    • 2018-09-22
    • 2016-01-26
    • 2015-08-13
    • 2021-02-23
    相关资源
    最近更新 更多