发送参数以在getInitialProps中获取以进行响应和nextjs

时间:2020-01-13 15:52:17

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

我正在发送一个参数给getInitialProp函数,以使效果变为正确的json。

这是我的代码: hepler.js->我在这里进行了获取。

export async function getEvents() {
  const res = await fetch("https://url/eventos.json");
  let new_data = await res.json();

  return { events: new_data.data };
}

export async function getDetails(slug) {
  const res = await fetch(`https://myurl/${slug}.json`);
  let data_detail_event = await res.json();
  return { data_detail_event };
}

_app.js // //我有getInitialProps并且效果很好

import App from "next/app";
import ContextProvider from "../provider/ContextProvider";
import fetch from "isomorphic-unfetch";
import {getEvents, getDetails} from '../helper/index'

export default class MyApp extends App {
  static async getInitialProps() {

    const events = await getEvents();
    return {
      events : events.events
    };
  }

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

pages / [id] .js

import { useRouter } from "next/router";
import Context from "../../config/Context";
/* Components */
import WordCounter from "../../components/word-counter/WordCounter";

function Post(props) {
  const router = useRouter();
  const context = React.useContext(Context);
  return (
    <React.Fragment>
     <WordCounter />
    </React.Fragment>
  );
}
Post.getInitialProps = async ({ query}) => {
  const detail = await getDetail(query.id) --> here I send the param and it seems never arrive to helper.js, why?
  return {detail}
}
export default  Post

问题出在哪里?救命! 谢谢!

1 个答案:

答案 0 :(得分:0)

我认为getInitialProps在服务器中运行,并且您的辅助函数未在其中加载。

在getInitialProps中使用访存。