我正在尝试遍历 Immutable.js 映射以呈现组件,但是尽管这是呈现,但它也在呈现页面的键。我不确定为什么。
render() {
const myMap = new Map({foo: '', bar: 'http://google.com/'})
const {showFoo, titleAndUrl} = this.props
return (
<ul style={[
styles.container,
showFoo && styles.container.inline,
]}>
{myMap.map((title, url) => this.renderTab(url, title))}
</ul>
)
}
renderTab(title, url) {
const {showFoo, isFoo} = this.props
return (
<li key="sb" style={[
styles.listItem,
showFoo && styles.listItem.inline,
]}>
<a
href={url}
key={title}
style={[
styles.link,
styles.activeLink,
showFoo && styles.link.inline,
]}
className={isFoo ? "style" : ''}>
{title}
</a>
</li>
)
}
}
两个名称和 url 被正确呈现,但是重复的键被呈现,即 foo 被呈现两次,bar 也是如此,但是 foo 和 bar 键之一没有样式,这表明它在 this 之外呈现.renderTab
呈现的 HTML:
<ul data-radium="true"
style="display: flex; align-items: center; padding: 0px; margin: 0px; list-style: none; width: 100%; border-top: 1px solid rgb(221, 221, 221); height: 48px;">
foo
<li data-radium="true" style="display: flex; width: 50%; height: 47px; cursor: default;"><a href=""
class=""
data-radium="true"
style="display: flex; justify-content: center; align-items: center; width: 100%; text-decoration: none; font-weight: 500; font-size: 16px; color: rgb(0, 31, 91); transition: color 0.1s linear;">foo</a>
</li>
bar
<li data-radium="true" style="display: flex; width: 50%; height: 47px; cursor: default;"><a
href="http://google.com" class="" data-radium="true"
style="display: flex; justify-content: center; align-items: center; width: 100%; text-decoration: none; font-weight: 500; font-size: 16px; color: rgb(0, 31, 91); transition: color 0.1s linear;">bar</a>
</li>
</ul>
最佳答案
您混淆了参数的顺序,将 title
分配给 url
,反之亦然。
此外,传递给 Immutable.Map.map 回调函数的参数是 (1) 值,(2) 键,因此第一个参数是您的 URL,第二个是您的标题。
更改调用 map
的行,如下所示:
{myMap.map((url, title) => this.renderTab(title, url))}
另一个问题是,您正在渲染的列表项元素都具有相同的键“sb”,只有“a”元素的键发生变化,但这甚至不需要。
将 renderTab
返回的 JSX 更改为:
<li key={title} style={[
styles.listItem,
showFoo && styles.listItem.inline,
]}>
<a
href={url}
style={[
styles.link,
styles.activeLink,
showFoo && styles.link.inline,
]}
className={isFoo ? "style" : ''}>
{title}
</a>
</li>
最后,主要的错误是你期望 Immutable.Map.map
返回一个数组,但它没有,它返回另一个不可变的映射,所以你必须转换返回的值使用 valueSeq 将 map 函数映射到数组和 toArray .
所以你的 map 语句实际上应该是这样的:
{myMap.map((url, title) => this.renderTab(title, url)).valueSeq().toArray()}
关于javascript - React 16 遍历 map 渲染键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47431231/