React组件映射时,如何在同文件内获取指定类型的pending属性值?
获取指定类型pending值的函数位置与实现
函数定义位置
根据你的组件类型(函数组件/类组件),选择对应的位置:
1. 函数组件(推荐)
在组件内部、map循环之外定义复用函数,可配合useCallback优化性能:
import { useCallback } from 'react'; const YourParentComponent = (props) => { // 定义通用的获取函数,可复用所有类型的pending值 const getPendingByType = useCallback((discoveriesByType, targetType) => { // 查找匹配type的项 const matchedItem = discoveriesByType.find(item => item.type === targetType); // 存在则返回pending,否则返回默认值0(可根据需求调整) return matchedItem?.pending ?? 0; }, []); // 无依赖,函数不会频繁重建 return ( <> {props.resultItemData.map((data, index) => { const carPending = getPendingByType(data.discoveriesByType, 'car'); const suvPending = getPendingByType(data.discoveriesByType, 'suv'); const atvPending = getPendingByType(data.discoveriesByType, 'atv'); return ( <ResultItem key={index} // 必须添加key,避免React渲染警告 carOnlyPendingValue={carPending} atvOnlyPendingValue={atvPending} suvOnlyPendingValue={suvPending} // 如果需要传递SUV的pending值 /> ); })} </> ); };
2. 类组件
将函数定义为类的实例方法,在render方法中调用:
import React from 'react'; class YourParentComponent extends React.Component { // 定义类方法 getPendingByType = (discoveriesByType, targetType) => { const matchedItem = discoveriesByType.find(item => item.type === targetType); return matchedItem ? matchedItem.pending : 0; }; render() { return ( <> {this.props.resultItemData.map((data, index) => { return ( <ResultItem key={index} carOnlyPendingValue={this.getPendingByType(data.discoveriesByType, 'car')} atvOnlyPendingValue={this.getPendingByType(data.discoveriesByType, 'atv')} suvOnlyPendingValue={this.getPendingByType(data.discoveriesByType, 'suv')} /> ); })} </> ); } }
额外说明
- 如果只是临时单次使用,也可以直接在
map内联处理(但复用性差,不推荐):<ResultItem suvOnlyPendingValue={ data.discoveriesByType.find(item => item.type === 'suv')?.pending ?? 0 } /> - 优先选择复用函数的写法,代码更清晰、易维护,且便于统一处理默认值逻辑。
内容的提问来源于stack exchange,提问作者Null
相关产品推荐
相关产品推荐

