首页 > 解决方案 > 在 Next Js 中为条件路由渲染 HTML

问题描述

我想弄清楚,为什么我的 HTML 没有为条件路由渲染,实际上,我有三个组件,一个是index.jsslug 目录中的父组件,两个是子组件country.jsprofile.js位于组件目录中。

我想为国家和个人资料组件保留相同的 URL 模式

domain.com/[countryCode]或者domain.com/[profileUsername]

请看下面的代码。

index.js

import React from 'react'
import { withRouter } from 'next/router'
import Country from '../../components/Country'
import Details from '../../components/Details'
class Type extends React.Component {
    constructor(props){
        super(props)
        this.state = {
            isCountry: ''
        }
    }
    checkCountry = (type) => {
        let isCountry = ''
        if(type){
            const countries = JSON.parse(localStorage.getItem('countries'))
            let countryCodes = []
            isCountry = countries.map(item => item.country.toLowerCase()).includes(type)
            this.setState({isCountry:isCountry})
        }
    }
    componentDidUpdate(prevProps){
        if(this.props.router.query.slug !== prevProps.router.query.slug){
            this.checkCountry(this.props.router.query.slug)
        }
    }
    componentDidMount(){
        this.checkCountry(this.props.router.query.slug)
    }
    render() {
        const {isCountry} = this.state
        return (
            <React.Fragment>
                {isCountry ? (
                    <Country/>
                ) : (
                    <Details/>
                )}
            </React.Fragment>
        )
    }
}

上面的代码按预期工作正常,但问题是,它没有将 HTML 返回到视图源代码中。请建议我该如何解决上述问题

标签: javascriptreactjsnext.js

解决方案


您应该使用getStaticProps提供关于您对 API 的请求的 next.js 信息,以便 next.js 可以缓存您的 API 响应(或类似功能,在文档中找到您需要的内容:https ://nextjs.org/docs/advanced-features/自动静态优化)。

可能有用:https ://nextjs.org/docs/advanced-features/static-html-export 。


推荐阅读