javascript - 在 Next Js 中为条件路由渲染 HTML
问题描述
我想弄清楚,为什么我的 HTML 没有为条件路由渲染,实际上,我有三个组件,一个是index.js
slug 目录中的父组件,两个是子组件country.js
,profile.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 返回到视图源代码中。请建议我该如何解决上述问题
解决方案
您应该使用getStaticProps
提供关于您对 API 的请求的 next.js 信息,以便 next.js 可以缓存您的 API 响应(或类似功能,在文档中找到您需要的内容:https ://nextjs.org/docs/advanced-features/自动静态优化)。
可能有用:https ://nextjs.org/docs/advanced-features/static-html-export 。
推荐阅读
- asynchronous - Julia @distributed:后续代码在所有工作人员完成之前运行
- docker - docker容器中的高效svn结帐
- dbus - gdbus introspect 与 --recurse 和 --xml 选项一起不递归
- grep - grep - 从字符串中获取单词
- javascript - Mongoose 5.3,this.getUpdate 不是函数
- html - CSS 定位无序列表中的顶级 p 标签
- typescript - 基于 Koa 使用默认和命名导出创建可扩展的打字稿包
- c - 如何从 C 中的链表构建霍夫曼树?
- c# - LINQ To Entities - M 到 M 选择返回比需要更多的列
- javascript - 在 PHP Laravel 中将变量从 foreach 循环传递到我的控制器