【问题标题】:Server side load a global component with Next.js in React服务器端在 React 中使用 Next.js 加载全局组件
【发布时间】:2019-03-13 12:27:38
【问题描述】:

我找不到任何人问这个问题的事实可能意味着我没有完全理解某些内容或者我正在使用错误的关键字进行搜索,所以如果这是一个问题,请不要咬我的头愚蠢的问题。

我正在粘贴代码的相关部分,但如果您想要完整示例的 repo,here it is。完整的问题将在底部。


这是我的文件夹结构:

server.js
/components
    Layout.js
/pages
    contact.js

server.js

// tells next which page to load
server.get("/contact/:id", (req, res) => {
    const actualPage = "/contact"
    const queryParams = {id: req.params.id}
    app.render(req, res, actualPage, queryParams)
})

// api uri for grabbing contacts from the database
server.get("/api/contact/:id", (req, res) => {
    Contact.findOne({first_name: req.params.id}, (error, contact) => {
        if (error) return next(error)
        res.status(200).json(contact)
    })
})

pages/contact.js

const Contact = props => (
    <Layout>
        <h1>{props.contact.first_name} {props.contact.last_name}</h1>
    </Layout>
)

// a static async call passes fetched data into the props
Contact.getInitialProps = async function (context) {
    const {id} = context.query
    const res = await fetch(`http://localhost:3000/api/contact/${id}`)
    const contact = await res.json()
    return {contact: contact}
}

components/Layout.js

const Layout = (props) =>
<div>
    <div>
        <Link href="/contact/John">
            <a>John</a>
        </Link>
        <Link href="/contact/Jed">
            <a>Jed</a>
        </Link>
        <Link href="/contact/Fred">
            <a>Fred</a>
        </Link>
    </div>
    {props.children}
</div>

我试图弄清楚是否可以动态查询数据库以构建数据库中文档的导航。我能想到的唯一方法是使用每个组件重新渲染整个导航,但这似乎非常不必要。同样,如果您想尝试一下代码,here's my example repo

【问题讨论】:

  • 您的意思是要从 DB 值构建动态导航,例如 /contact/John/contact/Jed/contact/X/contact/Y?或者你的意思是你想预加载一次所有的联系人,并通过某个 id 显示不同的联系人详细信息?
  • 我想根据 DB 值构建动态导航。

标签: javascript reactjs react-router server-side-rendering next.js


【解决方案1】:

我能想到的一种方法是使用 custom app.js 并添加 componentDidMount 方法(它只触发一次),您可以在其中获取所有联系人,将其存储在 app.js 状态中并将其传递给页面和组件。

_app.js

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

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};

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

    return { pageProps };
  }

  // store contacts in the state
  state = {
    contacts: undefined
  };

  componentDidMount() {
    // get contacts and store them in the _app.js state
    fetch('some-api/all-contacts-endpoint').then(contacts => {
       this.setState({ contacts });
    });
  }

  render() {
    const { Component, pageProps } = this.props;

    return (
      <Container>
        <Component {...pageProps} contacts={this.state.contacts} />
      </Container>
    );
  }
}

pages/contact.js

// contacts will be inside props here
const Contact = props => (
  <Layout contacts={props.contacts}>
    <h1>
      {props.contact.first_name} {props.contact.last_name}
    </h1>
  </Layout>
);

// a static async call passes fetched data into the props
Contact.getInitialProps = async function(context) {
  const { id } = context.query;
  const res = await fetch(`http://localhost:3000/api/contact/${id}`);
  const contact = await res.json();
  return { contact: contact };
};

components/Layout.js

const Layout = ({ contacts = [] }) => (
  <div>
    <div>
      {contacts.map(contact => (
        <Link key={contact.id} href={`/contact/${contact.id}`}>
          <a>{contact.name}</a>
        </Link>
      ))}
    </div>
    {props.children}
  </div>
);

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-08-14
    • 2021-08-30
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2022-11-10
    • 2018-08-24
    • 2021-01-08
    相关资源
    最近更新 更多