Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将Nextjs URL解析为选定组件_Javascript_Next.js - Fatal编程技术网

Javascript 将Nextjs URL解析为选定组件

Javascript 将Nextjs URL解析为选定组件,javascript,next.js,Javascript,Next.js,据我所知,通过将URL映射到pages文件夹中各自的文件来解析URL。因此,可以通过href=/about-us访问/about-us.js页面 我想创建多种语言,但不想复制必要的组件/JS文件。因此,假设我有一个about-us.js,包含以下内容: <Head title={meta}/> <Nav/> <MainContent language={lang}/> <Footer/> 如何将/pl/about-us映射到页面根目录中的/ab

据我所知,通过将URL映射到pages文件夹中各自的文件来解析URL。因此,可以通过href=/about-us访问/about-us.js页面

我想创建多种语言,但不想复制必要的组件/JS文件。因此,假设我有一个about-us.js,包含以下内容:

<Head title={meta}/>
<Nav/>

<MainContent language={lang}/>
<Footer/>

如何将/pl/about-us映射到页面根目录中的/about-us.js,而不在/pages/pl/中创建另一个about-us.js?

我能想到的解决方案之一是将该语言作为查询参数传递

范例

// code for page/about-us.js page
import { withRouter } from 'next/router';

const AboutUs = ({ router }) => {
  const { lang } = router.query;

  return <div>Welcome to next.js! Language = {lang}</div>;
};

export default withRouter(AboutUs);
或者,不必解析每个页面中的语言,您可以使用类似于下面的代码

// custom _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 }
  }

  state = {
    language: undefined
  };

  componentDidMount() {
    const { router } = this.props;

    this.setState({ language: router.query.lang });
  }

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

    return (
      <Container>
        <Component {...pageProps} language={this.state.langugage} />
      </Container>
    )
  }
}
因此,每个页面都将有作为参数传递的语言

希望这有帮助

更新:


要定制路由,您需要检查并编写一些

谢谢,但我想映射路由,因为资源比搜索引擎优化的查询字符串更好。哦,我明白了。我想这样你需要检查并写出一些@yayokperfect,后者很好用。也许你可以修改答案。
// custom _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 }
  }

  state = {
    language: undefined
  };

  componentDidMount() {
    const { router } = this.props;

    this.setState({ language: router.query.lang });
  }

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

    return (
      <Container>
        <Component {...pageProps} language={this.state.langugage} />
      </Container>
    )
  }
}