reactjs - React JS 中循环内的条件渲染
问题描述
我有来自我试图在表格中显示的外部 API 的数据。数据带有日期时间戳。
我想在表格中呈现数据,但其中有一个额外的行显示日期更改时的日期。
我试过的
- 我尝试更新 lastDate 道具值。
- 我尝试使用 (condition) 进行条件渲染?预期:render() 方法中的其他语法和变量。
- 我不知道如何跟踪当前的日期变量并在每次循环迭代时更新它。
- 我尝试将 DateRow 和 DataRow 拆分为单独的组件并传递日期,但状态没有持久化。
- 我不确定这样做的最佳做法是什么。或者,如果这只是一个坏主意。
import React from 'react';
import { Link } from 'react-router-dom';
import { Table } from 'react-bootstrap';
import * as helpers from '../../common/helpers';
export default class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(`https://api.example.com`)
.then(res => res.json())
.then(
(result) => {
this.setState({
data: result
});
}
)
}
render() {
const { data } = this.state;
return (
<>
<h4>Most Recent</h4>
<Table>
<thead>
<tr>
<th>Time</th>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
{data.map(newRow => (
// Here I'd like to conditionally render a row if there has been a change in day from the last row before rendering the next row.
// ie. if previousDate != currentDate
// <tr>
// <td>{helpers.getFormattedDate(newRow.time)}</td>
// <td></td>
// <td></td>
// </tr>
// Then render the following :
<tr key={newRow.id}>
<td>
{helpers.getFormattedTime(newRow.time)}
</td>
<td>
<Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
</td>
<td>
{/* Some more content here */}
</td>
</tr>
))}
</tbody>
</Table>
</>
);
}
}
这里的任何帮助将不胜感激,我对此感到有点迷茫。
谢谢!
解决方案
你可以通过结合两个特性在 React 中进行条件渲染:
一旦可以确定表达式的值,JavaScript 就会停止使用布尔运算符(如
&&
和)对表达式求值。||
例如,在 中,如果返回 false ( , , , ) 值,则永远不会调用func1() && func2()
该函数。同样,如果返回真值,则永远不会调用 in 。func2
func1
null
undefined
false
0
func1() || func2()
func2
func1
React 不会呈现虚假(除了
0
)值。
因此,在 React 中进行条件渲染的一种常见方法是执行以下操作:
<div>
{ isTrue && (
<MyConditionalComponent/>
)}
</div>
MyConditionalComponent
只有在真实的情况下才会呈现在哪里isTrue
。
在您的情况下,由于您使用的是map
,因此您可能还希望使用该Fragment
组件,该组件基本上允许您为map
. 或者,您可以使用 a reduce
,但为简单起见,我将仅展示一个带有 的示例map
:
<tbody>
{data.map((newRow, i) => (
<React.Fragment>
(i !== 0 && (getDate(newRow.time) !== getDate(data[i - 1].time))) && (
<tr>
<td>{helpers.getFormattedDate(newRow.time)}</td>
<td></td>
<td></td>
</tr>
)
<tr key={newRow.id}>
<td>
{helpers.getFormattedTime(newRow.time)}
</td>
<td>
<Link to={`/something`}>{helpers.getFormattedNumber(newRow.value)}</Link>
</td>
<td>
{/* Some more content here */}
</td>
</tr>
</React.Fragment>
))}
</tbody>
哪里getDate
会有一些函数只返回Date
对象的日期部分。
请注意,我们还使用回调的第二个参数 ( i
) map
,它是当前元素的索引,用于检查前一个元素的日期。
推荐阅读
- c# - ASP Core 3.1 程序使用的用户字符串的组合长度超过了允许的限制。尝试减少字符串文字的使用
- mongodb - 如何将 {useMasterKey: true} 传递给解析服务器 js 聚合查询?
- javascript - 如何使用节点 js 在 GraphQL 中获取响应状态?
- php - Laravel 7 - 如何使“记住我”功能正常工作?
- javascript - 除逗号后引号外的任何字符的正则表达式
- r - corrplot 中的 Spearman 相关图
- javascript - 使用 javascript 使用 Gmail API 显示邮件内容
- python - Gensim Mallet Wrapper:如何获取所有文档的主题权重?
- html - 如何使用nodejs在客户端下载文件
- amazon-web-services - 当服务(在 ecs fargate 上)返回 503 时,AWS 弹性负载均衡器能否将请求重定向到 lambda 函数