javascript - 使用循环和 ifs 在 componentDidMount 中设置状态
问题描述
我有一个提供新闻文章标签的提供商(包含新闻的列表)。如果它们超过三个,那么附加标签 (>3) 将被组合在一起(在示例代码中称为 plusTags)。我可以在控制台中看到我拥有所有标签,但它们没有正确分布。前任。
在第一页我有四个新闻,分布标签为“a,b,c”,b”,“ac”“b”。在下一页,新闻文章(显然)不同,但标签的分布与第一页上的相同(“a,b,c”,“b”,“ac”“b”),即使标签应该不同。所以分布遵循相同的模式。我怀疑这是我的“componentDidMount”函数中的代码,因为它在那里我分发所有标签。怀疑它可能会重复,因为这个函数会重复自己?
public componentDidMount(): void {
let tags = [];
let plusTags = [];
if (this.props.tags != null) {
if (this.props.tags.length > 0) {
for (var i = 0; i < 3; i++) {
if (this.props.tags[i] != undefined) {
tags.push(this.props.tags[i] + " ");
}
}
for (var j = this.props.tags.length - 1; j >= 3; j--) {
if (this.props.tags[i] != undefined) {
plusTags.push(this.props.tags[j] + " ");
}
}
} else {
tags = this.props.tags;
}
}
this.setState({
tags: tags,
plusTags: plusTags
});
}
在我的渲染中
public render(): React.ReactElement<INewsTagsProps> {
return <React.Fragment>
<div className={styles.tagContainer}>
{
this.state.tags ?
this.state.tags.map((t) => {
if (this.props.background == BackgroundType.None) {
return (
<a href={this.props.tagPageUrl + "?tag="+ t}>
<span className={styles.tagNewsTiles}>{t}</span>
</a>);
}
else {
return(
<a href={this.props.tagPageUrl + "?tag="+ t}>
<span className={styles.tagFollowedNews}>{t}</span>
</a>);
}
})
: null
}
{this.state.plusTags.length > 0 ?
<span className={`callout-target-${this.state.targetIndex} ${this.props.background == BackgroundType.None ? styles.tagNewsTiles : styles.tagFollowedNews}`}
onClick={(e) => {e.stopPropagation(); this.setState({plusTagsDialogOpen: true});}}>+ {this.state.plusTags.length}</span>
:
null
}
</div>
<Callout
className="ms-CalloutExample-callout"
gapSpace={0}
target={this.state.target}
onDismiss={() => this.closeDialog()}
hidden={!this.state.plusTagsDialogOpen}
isBeakVisible={true}
beakWidth={10}
directionalHint={DirectionalHint.topCenter}
>
<div className={styles.tagPopupWrapper}>
<div className={styles.tagPopupContainer}>
{this.state.plusTags ?
this.state.plusTags.map((t) => {
if (this.props.background == BackgroundType.None) {
return (
<a href={this.props.tagPageUrl+ "?tag="+t}>
<span className={styles.tagNewsTiles}>{t}</span>
</a>);
}
else {
return(
<a href={this.props.tagPageUrl+ "?tag="+t}>
<span className={styles.tagFollowedNews}>{t}</span>
</a>);
}
}):
null}
</div>
</div>
</Callout>
;
解决方案
推荐阅读
- javascript - 烧瓶与 Socket.io 崩溃
- python - 没有键值对的 Python 拆分嵌套字典
- regex - 有什么方法可以生成任意等价的正则表达式吗?
- spring - Spring Boot Restful API:具有关系的 DTO 使用 ModelMapper 转换为实体?
- javascript - 如何使用 mongoose 创建模块以共享不断变化的数据库连接
- python - 向数据框索引添加标识符
- c - 我在 C 中为日期使用什么格式说明符?
- server - 访问具有多个 IP 地址的 Ubuntu 20.04 服务器
- pandas - 在 Pyspark 中按级别绘制直方图
- reactjs - 对至少一个值为真的对象数组进行 YUP 验证