[英]React 16 iterating over map rendering key
我試圖遍歷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)鍵,因此fist參數是您的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和toArray將map函數返回的值轉換為數組。
因此,您的map語句實際上應如下所示:
{myMap.map((url, title) => this.renderTab(title, url)).valueSeq().toArray()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.