diff --git a/src/components/Comments/index.js b/src/components/Comments/index.js index 4d16cfa..4b9aa9e 100644 --- a/src/components/Comments/index.js +++ b/src/components/Comments/index.js @@ -1,33 +1,29 @@ 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); + const [mounted, setMounted] = useState(false); - // 检查是否在浏览器环境中 useEffect(() => { - setIsBrowser(true); - }, []); - - // 从 localStorage 加载评论 - useEffect(() => { - if (isBrowser) { - const savedComments = localStorage.getItem('docComments'); - if (savedComments) { + setMounted(true); + const savedComments = localStorage.getItem('docComments'); + if (savedComments) { + try { setComments(JSON.parse(savedComments)); + } catch (e) { + console.error('Failed to parse comments:', e); } } - }, [isBrowser]); + }, []); - // 保存评论到 localStorage const saveComments = (newComments) => { - if (isBrowser) { + try { localStorage.setItem('docComments', JSON.stringify(newComments)); + } catch (e) { + console.error('Failed to save comments:', e); } }; @@ -54,8 +50,7 @@ const Comments = () => { saveComments(updatedComments); }; - // 在服务器端渲染时不显示评论组件 - if (!isBrowser) { + if (!mounted) { return null; }