简体   繁体   English

在渲染表时反映“不变违规”

[英]React 'Invariant Violation' in rendering a table

I'm getting the following error when trying to add an onClick property to a <td> element inside of a table. 尝试将onClick属性添加到表内的<td>元素时,我收到以下错误。 Here is my error: 这是我的错误:

Invariant Violation: findComponentRoot(...) ... Unable to find element. 不变违规:findComponentRoot(...)...无法找到元素。 This probably means the DOM was unexpectedly mutated (eg, by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like ... or using non-SVG elements in an <svg> parent. 这可能意味着DOM意外地发生了变异(例如,通过浏览器),通常是因为在使用表时忘记了<tbody>,在<svg>父级中嵌套标签......或者使用非SVG元素。 Try inspecting the child nodes of the element with React ID. 尝试使用React ID检查元素的子节点。

I've read a few variants of the same problem, but most of the problems result from using improper table structure. 我已经阅读了相同问题的一些变体,但大多数问题都是由于使用不正确的表结构造成的。 My table is structured properly. 我的桌子结构合理。 Here is my full function: 这是我的全部功能:

render() {
    return (
        <table className="table table-hover">
            <thead>
                <tr>
                    <th>Field</th>
                    <th>Value</th>
                </tr>
            </thead>
            <tbody>
                {Object.keys(user).map(function(key) {
                    let val = user[key];
                    if (typeof val === 'string') {
                        return (
                            <tr key={user[key]}>
                                <th>{key}</th>
                                <td onClick={this.handleClick}>{val}</td>
                            </tr>
                        )
                    }
                }, this)}
            </tbody>
        </table>
    )
}

The error only exists when I set the onClick property, it runs without error when it's removed. 该错误在我设置onClick属性时存在,它在删除时运行时没有错误。

What's the cause of this error and how can I fix it? 这个错误的原因是什么,我该如何解决?

The problem was that user[key] was declared as a property of my <tr> . 问题是user[key]被声明为我的<tr>的属性。 One of the resulting values was a fairly lengthy string that React wouldn't accept as a valid key. 其中一个结果值是一个相当冗长的字符串,React不接受该字符串作为有效密钥。 Changing <tr key={i}> fixed the problem. 更改<tr key={i}>修复了问题。 I'm not sure why I was setting the key as anything else to begin with, but thought I'd share in case anyone else is getting a similar error. 我不确定为什么我要将密钥设置为其他任何东西,但我认为我会分享以防其他人得到类似的错误。

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

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