修复Valine静态路由重新加载

This commit is contained in:
tlyong1992
2022-05-27 10:13:08 +08:00
parent 8132a96b92
commit a36b7f2711

View File

@@ -1,24 +1,49 @@
import BLOG from '@/blog.config'
import { useRouter } from 'next/router'
import React from 'react'
import Valine from 'valine'
const ValineComponent = (props) => {
React.useEffect(() => {
const valine = Valine({
el: '#vcomments',
const router = useRouter()
const initValine = (url) => {
const valine = new Valine({
el: '#v-comments',
appId: BLOG.COMMENT_VALINE_APP_ID,
appKey: BLOG.COMMENT_VALINE_APP_KEY,
avatar: '',
path: url || router.asPath,
recordIP: true,
placeholder: BLOG.COMMENT_VALINE_PLACEHOLDER,
serverURLs: BLOG.COMMENT_VALINE_SERVER_URLS,
visitor: true
})
if (!valine) {
console.error('valine插件加载失败')
console.error('valine错误')
}
})
return <div id='vcomments'></div>
}
const updateValine = url => {
// 移除旧的评论区,否则会重复渲染。
const wrapper = document.getElementById('v-wrapper')
const comments = document.getElementById('v-comments')
wrapper.removeChild(comments)
const newComments = document.createElement('div')
newComments.id = 'v-comments'
newComments.name = new Date()
wrapper.appendChild(newComments)
initValine(url)
}
React.useEffect(() => {
initValine()
router.events.on('routeChangeComplete', updateValine)
return () => {
router.events.off('routeChangeComplete', updateValine)
}
}, [])
return <div id='v-wrapper'>
<div id='v-comments'></div>
</div>
}
export default ValineComponent