简体   繁体   中英

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. Here is my error:

Invariant Violation: findComponentRoot(...) ... Unable to find element. 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. Try inspecting the child nodes of the element with 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.

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> . One of the resulting values was a fairly lengthy string that React wouldn't accept as a valid key. Changing <tr key={i}> fixed the problem. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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