简体   繁体   English

React.js 数组 .push() 正在接受多个值

[英]React.js array .push() is taking multiple values

I am working on a simple blog website as my first Web Dev project.我正在一个简单的博客网站上工作,这是我的第一个 Web 开发项目。 In the page where I write a blog, I am using a simple svg icon with an onClick listener to add a paragraph to the blog.在我写博客的页面中,我使用一个带有 onClick 侦听器的简单 svg 图标向博客添加一个段落。 This works like Medium where when you click on the "+" icon, it adds a new paragraph for you to write.这就像 Medium,当您单击“+”图标时,它会添加一个新段落供您编写。 Here is the code of my onClick event listener function:这是我的 onClick 事件侦听器函数的代码:

function addNewPara() {
        // let newContent = {
        //     date: blogContent.date,
        //     author: blogContent.author,
        //     title: blogContent.author,
        //     contentArray: blogContent.contentArray.push("")
        // };
        // setBlogContent(newContent);

        setBlogContent(prevValue => {
            prevValue.contentArray.push("")
            return {
                ...prevValue,
            }
        });
    }

This has two ways where I update the state value.这有两种方法可以更新状态值。 The issue here is that when I click the plus icon and this method is triggered, it pushes two empty strings into the contentArray key.这里的问题是,当我单击加号图标并触发此方法时,它会将两个空字符串推送到contentArray键中。

If I uncomment and switch to the other method, I get the following error: TypeError: blogContent.contentArray.map is not a function如果我取消注释并切换到另一种方法, TypeError: blogContent.contentArray.map is not a function出现以下错误: TypeError: blogContent.contentArray.map is not a function

The TypeError occurs where I am using the array to render the relevant HTML elements. TypeError发生在我使用数组呈现相关 HTML 元素的地方。 What could be the issues behind this?这背后可能有什么问题?

这应该是你的可设置方法

setBlogContent({...blogContent, contentArray: [...blogContent.contentArray, "your new item"]})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM