Javascript 节点列表元素上的forEach()函数

Javascript 节点列表元素上的forEach()函数,javascript,reactjs,Javascript,Reactjs,我有一个函数将字符串转换为react组件和一个带有nodelist的元素变量,我需要使用forEach循环从一个元素创建两个组件 在这一刻,我得到了一个错误: TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method. 我不知道如何解决这些问题:( 我的职能: c

我有一个函数将字符串转换为react组件和一个带有nodelist的元素变量,我需要使用forEach循环从一个元素创建两个组件

在这一刻,我得到了一个错误:

TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
我不知道如何解决这些问题:(

我的职能:

    const htmlStrToReactComponent = (str) => {
        const dom = new DOMParser().parseFromString(str, 'text/html')

        const element = dom.documentElement.firstChild.childNodes // in this line I have for example 2x [object HTMLScriptElement]

        element.forEach(function (currentValue){ // loop to extract the two elements
            const NodeName = currentValue.nodeName.toLowerCase()

            const scriptAttributes = Object.fromEntries([...element.attributes]
                .map(({ nodeName, nodeValue }) => [nodeName, nodeValue]))

            return <NodeName {...scriptAttributes} />
        })
    }
const htmlstrotreactcomponent=(str)=>{
const dom=new DOMParser().parseFromString(str,'text/html')
const element=dom.documentElement.firstChild.childNodes//在这一行中,我有一个示例2x[object HTMLScriptElement]
forEach(函数(currentValue){//循环以提取这两个元素
const NodeName=currentValue.NodeName.toLowerCase()
const scriptAttributes=Object.fromEntries([…element.attributes]
.map({nodeName,nodeValue})=>[nodeName,nodeValue]))
返回
})
}

[…元素.属性]
修复为
[…当前值.属性]


解决方案2:如果您想将HTML字符串转换为React元素,可以尝试使用
.map()
而不是
.forEach()
?这些
返回的
不会在
.forEach()中执行任何操作
。您在哪个浏览器中运行代码?在哪一行抛出错误?我在Chrome中运行代码。错误与
const scriptAttributes=Object.fromEntries([…element.attributes])一致。