关于javascript:警告:flattenChildren(…):在REACTJS中遇到了两个具有相同键” false”的孩子

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

我正在尝试创建一个列表并使它可单击,以便一旦我单击某个项目,便会重定向到另一个页面

这是渲染方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 render() {
const quesItems = this.state.questions.map((question, i) => {
  return (
    <li key={this.props.account.id === question.expID}>
       {question.description}
   
</li>

  );
});
return (
 
     Answer the questions here!
   
<ul>

      {quesItems}
   
</ul>

 
);

} ??

但是,当我单击列表中的任何项目时,我都会收到以下警告。我该如何解决?

1
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.


表达式this.props.account.id === question.expID返回一个布尔值。 key道具通常不应为布尔值(只有两个不同的值)。 quesItems可能包含多个expID不等于this.props.account.id的项目。所有这些都将使用key={false}渲染,这是不允许的。关键道具的正确值可能只是问题id;

编辑:基于@Colin的建议,我添加了过滤逻辑。另请参见Array.prototype.filter()。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
render() {
    const questions = this.state.questions.filter(question => question.expID === this.props.account.id)

    return (
       
            Answer the questions here!
           
<ul>

                {questions.map(({id, description}) => (
                    <li key={id}>
                        {description}
                   
</li>

                ))}
           
</ul>

       
    );
}