将对象添加到状态的属性中,该属性是React

时间:2020-02-05 22:38:20

标签: javascript reactjs

这是我第一次尝试做一个React项目。我对它很陌生,所以我只是从其他YouTube频道中提取它,我敢肯定您会发现它很乱,因此我深表歉意。

我正在做一个博客项目,我想为每个帖子添加评论组件。我在线获取了一些对象用作帖子,但是由于没有注释属性,因此我尝试使用useEffect添加它。但是,在使用useState提交时,我无法添加评论。我一定使用不正确。我会在控制台中检查post对象,但是comment数组为空。

App.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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我认为问题在于您想在addedComments函数中设置注释。您没有在父函数中的任何地方调用该函数(当然,您可以只返回map函数,而不是将其放在另一个函数中)。此外,为了设置状态,最好提供与初始值相同的类型,在这种情况下,还需要显示一个数组。您为setComments钩子提供了一个空数组,因此您需要将值设置为数组并在其中传播当前注释,而不是在对象内部传播。

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

如果答案不能解决您的问题,我会更新。

答案 2 :(得分:0)

这里有两个问题。

  1. 函数addedComments从未被调用。
  2. setComments需要接受一系列评论。

addComment的这些更改应该可以解决您的问题。

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

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