Next.js:在静态导出期间将其他道具传递给页面吗?

我正在尝试静态导出next.js应用程序。文件说,网页对象只有两个值:pagequery有没有办法将其他道具传递到页面?

我已经尝试过使用query它,但似乎下一台路由器并不知道该路由的query对象。因此,它没有用。

换句话说,我在构建时有一个博客帖子列表,如何将它们内联到页面(页面组件)中?

我想每个路径react-static都有一个routeInfo.json预取的。我想知道next.js中是否有类似的东西。

番长神奇2020/03/24 17:30:39

UPD 12月4日19

有一个RFC getStaticProps可以解决此问题:https : //github.com/zeit/next.js/issues/9524


这就是我最后得到的。

_app.js:

import React from "react";
import App, { Container } from "next/app";

import fs from "fs";
import { resolve, join } from "path";

export default class extends App {
  static async getInitialProps({ Component, ctx }) {
    const { req, asPath } = ctx;
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    let p;
    if (req) {
      p = JSON.parse(
        fs.readFileSync(resolve(join("data", asPath, "route.json"))).toString()
      );
    } else {
      p = await (await fetch(`/data${asPath}/route.json`)).json();
    }

    return { pageProps: { ...pageProps, ...p } };
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    );
  }
}

在next.config.js中:

const fetch = require("isomorphic-unfetch");
const fs = require("fs");
const path = require("path");
const fse = require("fs-extra");
const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: false
});

module.exports = withBundleAnalyzer({
  webpack(config) {
    config.node = { fs: "empty", path: "empty" };
    return config;
  },
  async exportPathMap() {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts?_page=1"
    );
    const postList = await response.json();
    fs.writeFileSync(
      path.resolve(`data/route.json`),
      JSON.stringify({ postList }, null, 2)
    );
    for (let i = 0; i < postList.length; ++i) {
      const id = postList[i].id;
      const response = await fetch(
        `https://jsonplaceholder.typicode.com/posts/${id}`
      );
      const post = await response.json();
      const fn = path.resolve(`data/post/${id}/route.json`);

      await fse.outputFile(fn, JSON.stringify(post, null, 2));
    }

    const pages = postList.reduce(
      (pages, post) =>
        Object.assign({}, pages, {
          [`/post/${post.id}`]: {
            page: "/post"
          }
        }),
      {}
    );

    return Object.assign({}, pages, {
      "/": { page: "/" }
    });
  }
});