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

问题描述

PostList组件 当我添加createCFommonent时,我得到了太多的重新渲染错误。 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(''),此过程将无限期地执行,并且您将得到无限循环错误。因此,我的建议是永远不要在不使用useEffect或不满足任何特定条件的情况下设置状态。