diff --git a/src/components/Comments/index.js b/src/components/Comments/index.js index fbf44c9..4d16cfa 100644 --- a/src/components/Comments/index.js +++ b/src/components/Comments/index.js @@ -1,22 +1,34 @@ import React, { useState, useEffect } from 'react'; import styles from './styles.module.css'; +import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; const Comments = () => { + const {siteConfig} = useDocusaurusContext(); const [comments, setComments] = useState([]); const [newComment, setNewComment] = useState(''); const [name, setName] = useState(''); + const [isBrowser, setIsBrowser] = useState(false); + + // 检查是否在浏览器环境中 + useEffect(() => { + setIsBrowser(true); + }, []); // 从 localStorage 加载评论 useEffect(() => { - const savedComments = localStorage.getItem('docComments'); - if (savedComments) { - setComments(JSON.parse(savedComments)); + if (isBrowser) { + const savedComments = localStorage.getItem('docComments'); + if (savedComments) { + setComments(JSON.parse(savedComments)); + } } - }, []); + }, [isBrowser]); // 保存评论到 localStorage const saveComments = (newComments) => { - localStorage.setItem('docComments', JSON.stringify(newComments)); + if (isBrowser) { + localStorage.setItem('docComments', JSON.stringify(newComments)); + } }; const handleSubmit = (e) => { @@ -42,6 +54,11 @@ const Comments = () => { saveComments(updatedComments); }; + // 在服务器端渲染时不显示评论组件 + if (!isBrowser) { + return null; + } + return (