Javascript 服务器端使用React中的Next.js加载全局组件
事实上,我找不到任何人问这个问题,这可能意味着我没有完全理解某些东西,或者我正在用错误的关键字搜索,所以如果这是一个愚蠢的问题,请不要咬我的头 我正在粘贴代码的相关部分,但是如果您想要完整示例的回购。完整的问题将在底部。Javascript 服务器端使用React中的Next.js加载全局组件,javascript,reactjs,react-router,server-side-rendering,next.js,Javascript,Reactjs,React Router,Server Side Rendering,Next.js,事实上,我找不到任何人问这个问题,这可能意味着我没有完全理解某些东西,或者我正在用错误的关键字搜索,所以如果这是一个愚蠢的问题,请不要咬我的头 我正在粘贴代码的相关部分,但是如果您想要完整示例的回购。完整的问题将在底部。 以下是我的文件夹结构: server.js /components Layout.js /pages contact.js server.js // tells next which page to load server.get("/contact/:i
以下是我的文件夹结构:
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)
})
})
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}
}
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>
页面/contact.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)
})
})
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}
}
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>
我试图弄清楚是否可以动态查询数据库来构建数据库中文档的导航。我能想到的唯一方法是用每个组件重新渲染整个导航,但这似乎是非常不必要的。同样,如果您想尝试一下代码,.我可以想到的一种方法是使用并添加
componentDidMount
方法(只触发一次),在该方法中,您可以获取所有联系人,将其存储在app.js state中,并将其传递给页面和组件
\u 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>
);
}
}
// 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 };
};
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>
);
从“React”导入React;
从“next/App”导入应用程序,{Container};
导出默认类MyApp扩展应用程序{
静态异步getInitialProps({Component,router,ctx}){
让pageProps={};
if(Component.getInitialProps){
pageProps=等待组件.getInitialProps(ctx);
}
返回{pageProps};
}
//在状态中存储联系人
状态={
联系人:未定义
};
componentDidMount(){
//获取联系人并将其存储在_app.js状态
fetch('some-api/all contacts端点')。然后(contacts=>{
this.setState({contacts});
});
}
render(){
const{Component,pageProps}=this.props;
返回(
);
}
}
页面/contact.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>
);
}
}
// 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 };
};
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>
);
//联系人将位于此处的道具内
const Contact=props=>(
{props.contact.first_name}{props.contact.last_name}
);
//静态异步调用将获取的数据传递到props
Contact.getInitialProps=异步函数(上下文){
const{id}=context.query;
const res=等待取数(`http://localhost:3000/api/contact/${id}`);
const contact=wait res.json();
返回{contact:contact};
};
组件/Layout.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>
);
}
}
// 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 };
};
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>
);
const布局=({contacts=[]})=>(
{contacts.map(contact=>(
{contact.name}
))}
{props.children}
);
希望这有帮助 您的意思是要根据DB值构建动态导航,如
/contact/John
、/contact/Jed
、/contact/X
和/contact/Y
?或者你的意思是你想一次预加载所有联系人并通过某个id显示不同的联系人详细信息?我想从DB值构建一个动态nav。