“对象作为 React 子对象无效(发现:[对象错误])。如果您打算渲染子对象的集合,请改用数组” int React

问题描述 投票:0回答:1

嘿,我在 JSON.stringify 更新博客中遇到了问题,我不知道问题是什么

当单击编辑按钮时,表示对象作为反应子项无效

我一直在寻找解决方案,如果知道请告诉我

import { useState, useEffect } from 'react';
import { useAuthContext } from '../Hooks/useAuthContext';
import { useParams } from 'react-router-dom';
import { useCommentContext } from '../Hooks/useCommentContext';
const Comment = () => {
    const { user } = useAuthContext();
    const [Content, setContent] = useState('');
    const { id } = useParams();
    const { comments, dispatch } = useCommentContext();
    const [Error, setError] = useState(null);
    const [editingCommentId, setEditingCommentId] = useState(null);


    // Get all bogs
    useEffect(() => {
        const fetchcomment = async () => {
            if (!user) {
                setError('You must be logged in');
                return;
            }
            setError(null);
            const response = await fetch('/api/comment/' + id, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${user.token}`
                }
            })
            const json = await response.json();
            try {
                if (response.ok) {
                    dispatch({ type: 'SET_COMMENTS', payload: json })
                }
            } catch (error) {
                setError(error)
                console.log(error)
            }
        }
        fetchcomment();
    }, [user, id, dispatch]);
    // Post a new comment
    const handlePost = async (e) => {
        e.preventDefault();

        const response = await fetch('/api/comment/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${user.token}`
            },
            body: JSON.stringify({ Blog_id: id, author: user.username, Content })
        })
        const json = await response.json();
        try {
            if (response.ok) {
                dispatch({ type: 'CREATE_COMMENT', payload: json })
                console.log('Comment created successfully', json)
                setContent('')
            }
        } catch (error) {
            setError(error)
            console.log(error)
        }
    }

    // Update a comment
    const handleUpdate = async (id) => {
        if (!user) {
            setError('You must be logged in');
            return;
        }
        try {
            const response = await fetch('/api/comment/' + id, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${user.token}`
                },
                body: JSON.stringify({ Blog_id: id, author: user.username, Content })
            })
            const json = await response.json();
            if (response.ok) {
                dispatch({ type: 'UPDATE_COMMENT', payload: json })
                console.log('Comment updated successfully')
            }
        } catch (error) {
            setError(error)
            console.log('Error updating comment', error)
        }
    }
    // start editing a comment
    const startEditing = (id, Content) => {
        setEditingCommentId(id);
        setContent(Content);
    }
    // Delete a comment
    const handleDelete = async (id) => {
        if (!user) {
            setError('You must be logged in');
            return;
        }
        try {
            const response = await fetch('/api/comment/' + id, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${user.token}`
                }
            })
            const json = await response.json();
            if (response.ok) {
                dispatch({ type: 'DELETE_COMMENT', payload: json })
                console.log('Comment deleted successfully')
            }
        } catch (error) {
            setError(error)
            console.log('Error deleting comment', error)
        }
    }


    return (
        <div className="comment-section">
            <h1>Comments</h1>
            <div className="comment-form">
                <form>
                    <label>Enter Your Comment</label>
                    <input type="text" value={Content} placeholder="Enter your comment" onChange={(e) => setContent(e.target.value)} />
                    <button type="submit" onClick={editingCommentId ? handleUpdate : handlePost}>{editingCommentId ? 'edit' : 'Post'}</button>
                </form>
            </div>
            {comments && comments.map(comment => (
                <div key={comment._id} className="comment-container">
                    <h4>{comment.author}-{comment.createdAt}</h4>
                    <p>{comment.content}</p>
                    <div className="comment-icons">
                        <span className="material-symbols-outlined" onClick={() => startEditing(comment._id, comment.content)}>edit</span>
                        <span className="material-symbols-outlined" onClick={() => handleDelete(comment._id)}>delete</span>
                    </div>
                    {Error && <div className="error">{Error}</div>}
                </div>
            ))}
        </div>
    );
}
export default Comment;

更新博客中的 json stringify 出现问题我不知道问题是什么

我期待评论需要正确更新

reactjs react-hooks react-context react-reducer
1个回答
0
投票

错误似乎在对象中,当发生错误时,您将其传递到 div 中。这给出了您所看到的错误。为了解决这个问题,我会确保您实际上正在显示您想要显示的内容。如果 Error 是一个字符串,请将其初始化为空字符串而不是 null,它应该可以解析您所看到的内容。

© www.soinside.com 2019 - 2024. All rights reserved.