【发布时间】:2020-09-07 13:56:38
【问题描述】:
我有一个函数可以突出显示我的搜索字符串。它会抛出警告消息“警告:每个孩子都应该有一个唯一的“key”道具。检查 SearchItem.js 的渲染方法”。
出于某种原因,它在调试模式下工作得非常好。
但是,一旦我关闭远程调试并尝试在我的 TextInput 中搜索某些内容,它就会冻结。我什至无法导航返回。
我知道我们应该添加一个唯一索引或 ID 以使该警告消失。但即使在分配 id 之后它也不起作用。
现在我收到了这个警告“遇到了两个具有相同密钥的孩子,6b081863-7279-4e4a-999c-8e41c090a318。密钥应该是唯一的,以便组件在更新时保持其身份。”
我的代码:
render(){
getHighlightedText = text => { //highlight function
const {value} = this.props; // search string
const words = value.split(/\s+/g).filter(word => word.length);
const pattern = words.join('|'); // join it if search string is 2 words
const tex = escape(pattern);
const re = new RegExp(tex, 'gi')
const children = [];
let before, highlighted, match, pos = 0;
const matches = text.match(re);
if(matches != null){
for( match of matches ){
match = re.exec(text)
if(pos < match.index) {
before = text.substring(pos, match.index);
if(before.length){
children.push(before)
}
}
highlighted = <Text style={{ backgroundColor: 'coral'}}>{match[0]}</Text> // issue is here I need to add an index
children.push(highlighted);
pos = match.index + match[0].length;
}
}
if(pos < text.length){
const last = text.substring(pos);
children.push(last);
}
return <Text>{children}</Text>
}
.
.
.
.
.
return <Text>{getHighlightedText(alert}</Text>
}
现在,即使我添加了一个索引 - 每个项目的 id。还是不行!!!
const {id} = this.props;
highlighted = <Text style={{ backgroundColor: 'coral'}} key={id}>{match[0]}</Text>
我怎样才能做到这一点??????
【问题讨论】:
标签: javascript arrays reactjs react-native