React中useEffect与setState引发无限循环及评论实时展示问题求助
解决提交评论后实时展示且避免无限循环的问题
我需要实现提交评论后立即获取并展示该评论,但遇到了以下问题:
- 当
useEffect依赖allComments时,会引发无限循环,但能实时显示评论 - 把依赖改成空数组后,无限循环消失,但必须刷新页面才能看到新评论
- 尝试拆分
useEffect也没能实现实时展示
方法1:提交评论成功后主动调用获取评论的方法
核心思路是不要用allComments作为useEffect的依赖,而是在评论提交接口成功返回后,直接调用获取评论的函数,这样既不会触发无限循环,又能实时更新评论列表。
const [allComments, setAllComments] = useState([]); // 封装获取评论的函数 const fetchComments = async () => { const formData = new FormData(); // 填充formData数据.... try { const response = await axios.post(url, formData, { headers }); setAllComments(response.data); } catch(error) { console.log(error); } }; // 组件挂载时初始化评论列表 useEffect(() => { fetchComments(); }, []); // 提交评论的函数 const handleSubmitComment = async (newComment) => { try { // 调用提交评论的接口 await axios.post('/submit-comment', { content: newComment }, { headers }); // 提交成功后立即重新获取评论列表 fetchComments(); } catch(error) { console.error('提交评论失败:', error); } };
方法2:提交成功后直接更新本地状态(无需重新请求)
如果你的提交评论接口会返回新创建的评论数据,可以直接把它加到现有的allComments数组里,省去一次请求,效率更高。
const [allComments, setAllComments] = useState([]); // 组件挂载时初始化评论列表 useEffect(() => { const fetchData = async () => { const formData = new FormData(); // 填充formData数据.... try { const response = await axios.post(url, formData, { headers }); setAllComments(response.data); } catch(error) { console.log(error); } }; fetchData(); }, []); // 提交评论的函数 const handleSubmitComment = async (newComment) => { try { // 提交评论并获取返回的新评论数据 const response = await axios.post('/submit-comment', { content: newComment }, { headers }); const createdComment = response.data; // 把新评论加到列表最前面(或最后面,根据需求调整) setAllComments(prevComments => [createdComment, ...prevComments]); } catch(error) { console.error('提交评论失败:', error); } };
方法3:用触发变量控制重新请求
如果必须通过useEffect触发请求,可以新增一个状态变量作为触发条件,比如refreshCount,每次提交评论后更新这个变量,触发useEffect重新获取评论。
const [allComments, setAllComments] = useState([]); const [refreshCount, setRefreshCount] = useState(0); const fetchComments = async () => { const formData = new FormData(); // 填充formData数据.... try { const response = await axios.post(url, formData, { headers }); setAllComments(response.data); } catch(error) { console.log(error); } }; // 当refreshCount变化时重新获取评论 useEffect(() => { fetchComments(); }, [refreshCount]); // 提交评论的函数 const handleSubmitComment = async (newComment) => { try { await axios.post('/submit-comment', { content: newComment }, { headers }); // 更新触发变量,触发useEffect重新请求 setRefreshCount(prev => prev + 1); } catch(error) { console.error('提交评论失败:', error); } };
内容的提问来源于stack exchange,提问作者cindicate
相关产品推荐
相关产品推荐

