Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

javascript - Reactjs: Key undefined when accessed as a prop

Tools: Reactjs 0.14.0 Vanilla Flux

I need unique identifiers for 2 reasons:

  1. Child Reconciliation
  2. Keeping track of what child was clicked

So let's say I have a list of messages that looks like this:

[
    {
      id: 1241241234,  // <-----The unique id is kept here
      authorName: "Nick"
      text: "Hi!"
    },
    ...
]

And now I use a Array.prototype.map() to create "ownee" component (MessageListItem) inside of the owner component MessageSection

function getMessageListItem(message) {
    return (
        <MessageListItem key={message.id} message={message} />
    );
}

var MessageSection = React.createClass({
    render: function() {
        var messageListItems = this.state.messages.map(getMessageListItem);
        <div>
            {messageListItems }
        </div>
    }
});

But the this.props.key is undefined in the MessageListItem even though I know for a fact that is was defined when it was passed down.

var ConvoListItem = React.createClass({
    render: function() {
        console.log(this.props.key); // Undefined
    }
});

I'm guessing there is a reason that React is not letting key be used as a prop.

Question:

If I can't use key as a prop, then what is the proper way to handle the duality need of keying and setting unique identifiers on a dynamic list of child elements that contain state?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

key and ref aren't really 'props'. They're used internally by react and not passed to components as props. Consider passing it as a prop such as 'id'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...