Understanding unique keys for array children in React.js

后端 未结 12 1328
时光取名叫无心
时光取名叫无心 2020-11-21 05:45

I\'m building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I\'m stil

相关标签:
12条回答
  • 2020-11-21 06:28

    Just add the unique key to the your Components

    data.map((marker)=>{
        return(
            <YourComponents 
                key={data.id}     // <----- unique key
            />
        );
    })
    
    0 讨论(0)
  • 2020-11-21 06:29

    Best solution of define unique key in react: inside the map you initialized the name post then key define by key={post.id} or in my code you see i define the name item then i define key by key={item.id}:

    <div className="container">
                    {posts.map(item =>(
    
                        <div className="card border-primary mb-3" key={item.id}>
                            <div className="card-header">{item.name}</div>
                        <div className="card-body" >
                    <h4 className="card-title">{item.username}</h4>
                    <p className="card-text">{item.email}</p>
                        </div>
                      </div>
                    ))}
                </div>

    0 讨论(0)
  • 2020-11-21 06:31

    Check: key = undef !!!

    You got also the warn message:

    Each child in a list should have a unique "key" prop.
    

    if your code is complete right, but if on

    <ObjectRow key={someValue} />
    

    someValue is undefined!!! Please check this first. You can save hours.

    0 讨论(0)
  • 2020-11-21 06:38
    var TableRowItem = React.createClass({
      render: function() {
    
        var td = function() {
            return this.props.columns.map(function(c, i) {
              return <td key={i}>{this.props.data[c]}</td>;
            }, this);
          }.bind(this);
    
        return (
          <tr>{ td(this.props.item) }</tr>
        )
      }
    });
    

    This will sove the problem.

    0 讨论(0)
  • 2020-11-21 06:41

    I fixed this using Guid for each key like this: Generating Guid:

    guid() {
        return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
            this.s4() + '-' + this.s4() + this.s4() + this.s4();
    }
    
    s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    

    And then assigning this value to markers:

    {this.state.markers.map(marker => (
                  <MapView.Marker
                      key={this.guid()}
                      coordinate={marker.coordinates}
                      title={marker.title}
                  />
              ))}
    
    0 讨论(0)
  • 2020-11-21 06:47

    I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.

    0 讨论(0)
提交回复
热议问题