嗨,我正在做一些函数来对从API接收的值进行排序,当我完成时,一切都很好。但是后来我开始得到奇怪的console.log消息,即使我的代码中没有任何东西(在制作东西之后删除每一个)。我还有一条消息,即我没有设置关键属性。他们的来源也来自其他组成部分,我不知道为什么。下面我发送图片和代码。
render() {
const {
activeSurveys, CategoryList, IDList, activeCategory
} = this.state;
return (
<div className="section" id="Surveys">
<h1>
Categories of surveys
</h1>
<h4>
Choose one to fill and contribute!
</h4>
<div className="row">
<div className="col-sm-6">
{CategoryList.map((element, index, array) => (
<div
key={keyIndex(array, index)[index].id} // Key creator from external library
onClick={() => this.setActiveCategory(element)}
className={activeCategory === element ? 'CategoryElementActive' : 'CategoryElement'}
>
{element}
</div>
))}
</div>
<div className="col-sm-6">
<h3>
Surveys to fill
</h3>
<div className="glyphicon glyphicon-arrow-down" />
{activeSurveys.map((element, index, array) => (
<div key={keyIndex(array, index)[index].id}>
{element.Topic}
</div>
))}
</div>
</div>
</div>
);
}
当我点击index.js:22时,它需要我从react-key-index库文件https://www.npmjs.com/package/react-key-index:
我发现问题在于为第二个列表创建一个密钥。这可能是由于它的内容。第一个是activeSurveys数组,第二个是CategoryList
PS。我是React的新手,所以如果我一般做错了,我会很感激任何更正。
编辑:问题解决了。在activeSurveys数组中已经有一个唯一的ID属性,因此keyIndex函数不仅无用,而且可能必须在不同命名的属性下创建一个键。谢谢大家的帮助!
要使用react-key-index
,您必须使用以下代码:arr = keyIndex(arr, 1);
此代码为简单数组添加和id,为其他数组添加_objName。
在简单的数组中要小心:
['val1','val2']
改变了
[
{
id: 'kRf6c2fY',
value: 'val1'
},
{
id: 'lYf5cGfM',
value: 'val2'
}
]
所以使用这段代码:
render() {
const {
activeSurveys, CategoryList, IDList, activeCategory
} = this.state;
CategoryList = keyIndex(CategoryList, 1); // *****
activeSurveys = keyIndex(activeSurveys, 1); // *****
return (
<div className="section" id="Surveys">
<h1>
Categories of surveys
</h1>
<h4>
Choose one to fill and contribute!
</h4>
<div className="row">
<div className="col-sm-6">
{CategoryList.map((element, index, array) => (
<div
key={element.id} // id added by keyIndex()
onClick={() => this.setActiveCategory(element.value)} // use element.value !!!
className={activeCategory === element.value ? 'CategoryElementActive' : 'CategoryElement'}
>
{element.value}
</div>
))}
</div>
<div className="col-sm-6">
<h3>
Surveys to fill
</h3>
<div className="glyphicon glyphicon-arrow-down" />
{activeSurveys.map((element, index, array) => (
<div key={element._Topic}> // _Topic added by keyIndex()
{element.Topic}
</div>
))}
</div>
</div>
</div>
);