React中如何在map函数中添加条件,仅显示日期匹配的列表项
需求说明
我用React的map函数渲染列表项,现在需要添加判断逻辑,只显示与指定日期匹配的项。
以下是当前的map函数代码:
function Feed(props) { console.table(props.data); const number=""; return ( <> { props.data.map(item=> ( <> <div className="taskcolorback-div" /> <button className="taskcolor-button" /> <input className="tasktext-b" defaultValue={item.fields.Title}></input> <button className="taskwhite-button" /> <b className="timeinline">{item.fields.Hours}Hr</b> <img className="vector-icon" alt="" src="icons8-chevron-right-64.png" /> </> )) } </> ) }
解决方案
方式1:先过滤数据再渲染(推荐)
先通过filter方法筛选出日期匹配的项,再对筛选后的结果执行map渲染,减少不必要的DOM渲染操作。
假设目标日期通过props.targetDate传入,每个列表项的日期字段为item.fields.Date,修改后代码如下:
function Feed(props) { console.table(props.data); const number=""; // 筛选出与目标日期匹配的项 const filteredItems = props.data.filter(item => { // 根据实际日期格式调整匹配逻辑,比如统一转成YYYY-MM-DD字符串比较 return item.fields.Date === props.targetDate; }); return ( <> { filteredItems.map(item=> ( <> <div className="taskcolorback-div" /> <button className="taskcolor-button" /> <input className="tasktext-b" defaultValue={item.fields.Title}></input> <button className="taskwhite-button" /> <b className="timeinline">{item.fields.Hours}Hr</b> <img className="vector-icon" alt="" src="icons8-chevron-right-64.png" /> </> )) } </> ) }
方式2:在map中添加条件渲染
如果需要保留原数组遍历逻辑,可在map内部通过判断决定是否渲染当前项:
function Feed(props) { console.table(props.data); const number=""; return ( <> { props.data.map(item=> { // 仅当日期匹配时返回渲染内容,否则返回null不渲染 if (item.fields.Date === props.targetDate) { return ( <> <div className="taskcolorback-div" /> <button className="taskcolor-button" /> <input className="tasktext-b" defaultValue={item.fields.Title}></input> <button className="taskwhite-button" /> <b className="timeinline">{item.fields.Hours}Hr</b> <img className="vector-icon" alt="" src="icons8-chevron-right-64.png" /> </> ) } return null; }) } </> ) }
注意事项
- 请根据实际的日期字段名、目标日期传递方式调整代码中的对应部分。
- 如果日期是
Date对象格式,需注意时间部分的影响,建议统一转成字符串格式(如YYYY-MM-DD)后再比较,避免因时分秒不一致导致匹配失败。
内容的提问来源于stack exchange,提问作者Jasim Hasan Jasim
相关产品推荐
相关产品推荐

