double
pfqgauxfb 2 months ago
parent 76c106bf53
commit faf4222020

@ -1,33 +1,29 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import styles from './styles.module.css'; import styles from './styles.module.css';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
const Comments = () => { const Comments = () => {
const {siteConfig} = useDocusaurusContext();
const [comments, setComments] = useState([]); const [comments, setComments] = useState([]);
const [newComment, setNewComment] = useState(''); const [newComment, setNewComment] = useState('');
const [name, setName] = useState(''); const [name, setName] = useState('');
const [isBrowser, setIsBrowser] = useState(false); const [mounted, setMounted] = useState(false);
// 检查是否在浏览器环境中
useEffect(() => { useEffect(() => {
setIsBrowser(true); setMounted(true);
}, []);
// 从 localStorage 加载评论
useEffect(() => {
if (isBrowser) {
const savedComments = localStorage.getItem('docComments'); const savedComments = localStorage.getItem('docComments');
if (savedComments) { if (savedComments) {
try {
setComments(JSON.parse(savedComments)); setComments(JSON.parse(savedComments));
} catch (e) {
console.error('Failed to parse comments:', e);
} }
} }
}, [isBrowser]); }, []);
// 保存评论到 localStorage
const saveComments = (newComments) => { const saveComments = (newComments) => {
if (isBrowser) { try {
localStorage.setItem('docComments', JSON.stringify(newComments)); localStorage.setItem('docComments', JSON.stringify(newComments));
} catch (e) {
console.error('Failed to save comments:', e);
} }
}; };
@ -54,8 +50,7 @@ const Comments = () => {
saveComments(updatedComments); saveComments(updatedComments);
}; };
// 在服务器端渲染时不显示评论组件 if (!mounted) {
if (!isBrowser) {
return null; return null;
} }

Loading…
Cancel
Save