简体   繁体   中英

Warning: flattenChildren(…): Encountered two children with the same key, `false` in REACTJS

I am trying to create a list and make it clickable so that once i click on an item i get redirect to another page

here is the render method

 render() {
const quesItems = this.state.questions.map((question, i) => {
  return (
    <li key={this.props.account.id === question.expID}>
      <a href={`/ans/${question.id}`}> {question.description}</a>
    </li>
  );
});
return (
  <div>
    <h1> Answer the questions here!</h1>
    <ul>
      {quesItems}
    </ul>
  </div>
);

}

However i am getting the following warning when i click on any item on the list. How can i fix it?

index.js:2177 Warning: flattenChildren(...): Encountered two children with the same key, `false`. Child keys must be unique; when two children share a key, only the first child will be used.

The expression this.props.account.id === question.expID returns a boolean value. The key prop should usually not be a boolean (there are only two distinct values). Probably quesItems contains multiple items whose expID does not equal this.props.account.id . All those will render with key={false} which is not allowed. The correct value for a key prop is probably just the question id ;

EDIT : Based on the suggestion of @Colin I added the filtering logic. Also see Array.prototype.filter() .

render() {
    const questions = this.state.questions.filter(question => question.expID === this.props.account.id)

    return (
        <div>
            <h1>Answer the questions here!</h1>
            <ul>
                {questions.map(({id, description}) => (
                    <li key={id}>
                        <a href={`/ans/${id}`}>{description}</a>
                    </li>
                ))}
            </ul>
        </div>
    );
}

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