当我在map函数中添加Component CommentCreate时,我得到了太多的重新渲染,并进入了无限循环



PostList组件当我添加createCFommcomponent时,我会得到太多的重新渲染错误。React限制渲染次数,以防止出现无限循环。

import React,{useState,useEffect} from 'react';
import axios from 'axios'
import './PostList.css'
import CommentCreate from './CommentCreate';
const PostList = () => {
const [ptitle,setPtitle]=useState({});
const fetchPost = async ()=> {
const res=await axios.get('http://localhost:8000/posts')
setPtitle(res.data)
}
useEffect(() => {
fetchPost()
}, [])

const renderedPost = Object.values(ptitle).map((post) => {
return (
<div
className="card"
style={{ width: "30%", marginBottom: "20px" }}
key={post.id}
>
<div className="card-body">
<h3>{post.title}</h3>
<CommentCreate postId={post.id} />
</div>
</div>
);
});
return (
<div>
<h1>Post List</h1>
{renderedPost}
</div>
);
}
export default PostList;

createComment组件这是提供的组件。请考虑向树中添加错误边界以自定义错误处理行为。

import React,{useState} from 'react';
import axios from 'axios'
import './CommentCreate.css'
const CommentCreate = ({postId}) => {
const [comment, setComment]=useState('')
const createComment = async (e) =>{
e.preventDefault();
await axios.post(`http://localhost:9000/post/${postId}/comment`, {
comment,
});
}
setComment('')
return (
<div>
<input value={comment} onChange={e =>{
setComment(e.target.value)
}} placeholder="Create a Comment here" />
<button class="btn btn-primary" onClick={createComment}>
Comment
</button>
</div>
);
}
export default CommentCreate;
```

问题

createComment由父级更新,并调用setComment,这将触发再次调用setComment的重新渲染。因此,一个无限的重新渲染。

解决方案

将您的setComment放置在createComment函数中。

const createComment = async (e) =>{
e.preventDefault();
await axios.post(`http://localhost:9000/post/${postId}/comment`, {
comment,
});

setComment('')
}

您正在全局设置状态setComment('')。如果只想在组件装载时设置状态,请考虑使用useEffect。使用以下片段:

useEffect(() => setComment(''), []);

全局设置状态将导致组件重新渲染,并在重新渲染时再次调用setComment("(,此过程将无限期执行,您将得到当前的infint循环错误。所以我的建议是,在不使用useEffect或不满足任何特定条件的情况下,永远不要设置状态。

最新更新