【问题标题】:Add object to a state's property which is an array in React将对象添加到状态的属性中,该属性是 React 中的数组
【发布时间】:2020-02-05 22:38:20
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

        这里有两个问题。

        1. 永远不会调用函数addedComments
        2. setComments 需要取一个 cmets 数组。

        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}
                            }
                        ])
                    }
                })
            }
        

        【讨论】:

          猜你喜欢
          • 2017-07-28
          • 2020-08-09
          • 2019-12-13
          • 2015-11-15
          • 2021-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多