首页 > 解决方案 > 将对象添加到状态的属性中,该属性是 React 中的数组

问题描述

这是我第一次尝试做一个 React 项目。我对它很陌生,所以我只是根据不同的 youtube 频道来制作它,我相信你会觉得它很乱,所以我很抱歉。

我正在做一个博客项目,我想为每篇文章制作一个评论组件。我在网上获取了一些对象用作帖子,但由于没有评论属性,我尝试使用 useEffect 添加它。但是,使用 useState 提交时,我无法添加到评论中。我一定是用错了。我会在控制台中检查帖子对象,但评论数组是空的。

应用程序.js

const App = () => {
    const [posts, setPosts] = useState([]);
    const [isLoading, setIsLoading] = useState(true)
    const [showForm, setShowForm] = useState(false)
    const [comments, setComments] = useState([])

    //fetch
    useEffect( () => {
        fetch("https://jsonplaceholder.typicode.com/posts")
        .then(res => res.json())
        .then(posts => {
            setIsLoading(false)
            posts = posts.map(post => {
                post.comment = comments;
                return post
            })
            setPosts(posts.slice(0, 1))
        })
    }, [])

    //add comment
    const addComment = (e, {title}, id) => {
        e.preventDefault()
        console.log("Comment: ", title)
        console.log("ID of post: ", id)

        const addedComments = posts.map(post => {
            if(post.id === id) {
                setComments(
                    ...comments,
                    {
                        id: uuid.v4,
                        title: {title}
                    }
                )
            }
        })
    }

CommentForm.js

const CommentForm = ({id, addComment}) => {
    const commentItems = <Comments />

    const [commentData, setCommentData] = useState({
        title: "",
    })

    const {title} = commentData

    const onChangeHandler = (e) => {
        setCommentData({
            ...commentData,
            [e.target.name] : e.target.value
        })
    }

    return (
        <div>
            <form onSubmit={ (e) => addComment(e, commentData, id) }>
                {JSON.stringify(commentData)}
                <div className="form-group">
                    <label htmlFor="title">Add comment:</label>
                    <input 
                    type="text" 
                    name="title" 
                    value={title}
                    onChange={ (e) => onChangeHandler(e)}
                    />
                    <button>Submit</button>
                    { commentItems }
                </div>
            </form>
        </div>
    )
}

控制台输出

App.js:64 Comment:  Test comment

App.js:67 ID of post:  1

App.js:26 
[{…}]
0:
userId: 1
id: 1
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
body: "quia et suscipit↵suscipit recusandae consequuntur expedita et cum↵reprehenderit molestiae ut ut quas totam↵nostrum rerum est autem sunt rem eveniet architecto"
comment: Array(0)
    length: 0
    __proto__: Array(0)
__proto__: Object
length: 1

标签: javascriptreactjs

解决方案


您破坏数组的方式似乎不正确

if (post.id === id) {
      setComments([
        ...comments,
        {
          id: uuid.v4,
          title: { title },
        },
      ]);
    }

推荐阅读