React类组件中如何移除数组对象的重复值?
解决React类组件渲染数组出现重复内容的问题
问题原因
- key属性不唯一:你使用
item.id作为React元素的key,但数组中存在多个相同id的项,导致React无法正确区分每个元素,可能引发渲染异常。 - 数据本身存在重复:接口返回的
customer数组里包含重复对象(比如输出中id=2的两条相同记录),需要先对数据去重。
解决方案
1. 对接口返回的数据去重
在componentDidMount中设置state前,先处理数据确保每个对象唯一:
componentDidMount() { axios .get("http://localhost:4000/customer/show", { responseType: "json" }) .then(response => { // 用id+createdAt作为唯一标识,过滤重复项 const uniqueCustomerMap = {}; response.data.forEach(item => { const uniqueKey = `${item.id}-${item.createdAt}`; if (!uniqueCustomerMap[uniqueKey]) { uniqueCustomerMap[uniqueKey] = item; } }); // 将对象转为数组 const uniqueCustomers = Object.values(uniqueCustomerMap); this.setState({ customer: uniqueCustomers }); }); }
2. 设置唯一的key属性
渲染数组时,使用id和createdAt的组合作为key,确保每个元素的key唯一:
render() { return ( <> {this.state.customer?.map((item) => { const uniqueKey = `${item.id}-${item.createdAt}`; return ( <div key={uniqueKey}> <div> Time of Visit: {moment(item.createdAt).format('hh:mm A')} </div> </div> ); })} </> ); }
补充说明
如果业务逻辑中同一个id只应对应一条记录,优先检查后端接口,确保返回数据无重复,这是从根源解决问题的方式。另外,避免使用数组索引index作为key,当数组元素顺序变化时会引发不必要的重新渲染,影响性能。
内容的提问来源于stack exchange,提问作者user20183888
相关产品推荐
相关产品推荐

