double
pfqgauxfb 2 months ago
parent 76c106bf53
commit faf4222020

@ -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;
}

Loading…
Cancel
Save