当我添加 createCFommonent 时,PostList 组件出现了太多的重新渲染错误。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 Component 这是给出的组件 考虑在树中添加错误边界以自定义错误处理行为。
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;
```