javascript - 在数组中“推送” JSX 元素时反应变量评估
问题描述
我在数组中推送 JSX 元素
for (category of this.state.categories) {
categories.push(
<li>
<label
className="tree-toggler nav-header list-group-item"
onClick={() => this.showHideConnectorNames(category)}
>
{category}
</label>
<ul
className="tree ul-no-style"
id={category+'Connectors'}
>
</ul>
</li>
);
}
问题是方法调用中的category
变量评估为数组中的最后一个(因此所有元素都是“cat2”)。它在所有其他地方都被正确评估,例如在.this.showHideConnectorNames(category)
category
this.state.categories
<label>
所以我必须这样做:
for (category of this.state.categories) {
if (category === 'cat1')
categories.push(
<li>
<label
className="tree-toggler nav-header list-group-item"
onClick={() => this.showHideConnectorNames('cat1')}
>
{category}
</label>
<ul
className="tree ul-no-style"
id={category + 'Connectors'}
>
</ul>
</li>
);
else if (category === 'cat2')
categories.push(
<li>
<label
className="tree-toggler nav-header list-group-item"
onClick={() => this.showHideConnectorNames('cat2')}
>
{category}
</label>
<ul
className="tree ul-no-style"
id={category + 'Connectors'}
>
</ul>
</li>
);
else
categories.push(
<li>
<label
className="tree-toggler nav-header list-group-item"
onClick={() => this.showHideConnectorNames(category)}
>
{category}
</label>
<ul
className="tree ul-no-style"
id={category + 'Connectors'}
>
</ul>
</li>
);
}
这是一个 React 问题还是我做错了什么?
解决方案
不确定构建后要对数组做什么,但我认为使用map
调用会更有效率。只需将其放在您要呈现列表项的任何地方的 return 语句中:
<ul>
{this.state.categories.map(cat => (
// your li has a missing key property
<li>
<label
className="tree-toggler nav-header list-group-item"
onClick={() => this.showHideConnectorNames(cat)}
>
{cat}
</label>
<ul
className="tree ul-no-style"
id={cat + 'Connectors'}
></ul>
</li>
))}
</ul>
推荐阅读
- kubernetes - 如何在单个 openshift yaml 模板中拥有多种对象类型?
- botframework - Microsoft Chatbot 的自定义聊天界面
- c# - 我可以使用不带 Equals 的 GetHashCode 吗?
- python - 绘制熊猫数据帧中的 Numpy 数组命令
- mysql - 可重复读取隔离级别 SELECT vs UPDATE...WHERE
- python - 迭代匹配子字符串,然后删除匹配项
- bash - 当一个程序在链中失败时如何停止重定向标准输出?
- spring - 创建名为“vendorController”的 bean 时出错:通过字段“vensorinterface”表达的依赖关系不满足;
- regex - 用于路径验证的正则表达式
- python - AttributeError:“系列”对象没有属性“isoweekday”