鉴于这条路线:
import { Router } from 'express'
const router = new Router()
const staticPages = [
'privacy',
'terms'
]
staticPages.forEach(page => {
router.get(`/${page}`, (req, res) => {
res.render('base', { bundle: 'static' })
})
})
export default router
我需要从${page}
文件动态构建一个使用路径dangerouslySetInnerHTML
到.pug
的组件。这就是我调用该组件的页面:
import React from 'react'
import ReactDOM from 'react-dom'
import Page from 'app/components/base-page'
import Static from 'app/components/static'
let page =
ReactDOM.render(
<Page >
<Static content={this.route} />
</Page>,
document.getElementById('content')
)
需要从路径控制器中提取参数content={this.route}
并匹配${page}
,以便组件<Static content={this.route} />
知道哪个.pug
文件到dangerouslySetInnerHTML
。怎么办呢?
编辑:为了澄清,组件本身看起来像这样..
export default class Static extends Component {
componentWillMount () {
this.setState({
__html: ''
})
let page = '/content/terms'
got({page})
.then(resp => {
console.log(resp)
return resp
})
.then(content => {
this.setState({
__html: content
})
})
.catch((err) => {
console.log(err)
})
}
render () {
return (
<div dangerouslySetInnerHTML={this.state} />
)
}
}
我还为terms.html添加了另一条路线:
import { Router } from 'express'
const router = new Router()
const staticPages = [
'privacy',
'terms'
]
staticPages.forEach(page => {
router.get(`/content/${page}`, (req, res) => {
res.send(`content/${page}.html`)
console.log(req, res)
})
})
export default router
答案 0 :(得分:0)
使用2个不同的快速路由器,如下所示:
静电content.js
import { Router } from 'express'
const router = new Router()
const staticPages = [
'privacy',
'terms'
]
staticPages.forEach(page => {
router.get(`/content/${page}`, function (req, res) {
res.render(`content/${page}`, function (err, html) {
console.log(err)
res.send(html)
})
})
})
export default router
static.js
import { Router } from 'express'
const router = new Router()
const staticPages = [
'privacy',
'terms'
]
staticPages.forEach(page => {
router.get(`/${page}`, (req, res) => {
res.render('base', { bundle: 'static' })
})
})
export default router
这是页面和组件jsx:
静电page.jsx
import React from 'react'
import ReactDOM from 'react-dom'
import Page from 'app/components/base-page'
import Static from 'app/components/static'
let page = document.location.pathname
ReactDOM.render(
<Page >
<Static content={page} />
</Page>,
document.getElementById('content')
)
静电component.jsx
import React, { Component } from 'react'
import got from 'got'
export default class Static extends Component {
componentWillMount () {
this.setState({
__html: ''
})
let page = '/content' + this.props.content
got(page)
.then(resp => {
return resp.body
})
.then(content => {
this.setState({
__html: content
})
})
.catch((err) => {
console.log(err)
})
}
render () {
return (
<div dangerouslySetInnerHTML={this.state} />
)
}
}