我有一个通过API提取的项目列表,该列表按字母顺序排序,但是我想在列表项目上方添加标题。例如下面的HTML结构
<h4> A</h4 >
<ul>
<li>Apple</li>
<li>Ant</li>
</ul>
<h4>B</h4>
<ul>
<li>Babel</li>
<li>Ball</li>
</ul>
到目前为止,我已经在功能中映射了以下项目列表:
filterItems = (itemList) => {
result = result.map((item, index) => (
<li className="brand-item" key={index}><a href="#">
<img onError={this.nobrandimage} src={item.thumbnail} className="img-responsive" /></a>
</li>
))
return result;
}
以下是我的渲染功能:
render(){
//code to get the letterkey, I am not sure how to put this in map function to render**
var letters = '', groups = {};
for (var i = 0, len; i < len; i++) {
var letterKey = brands[i].name.charAt(0).toLowerCase(); // get the first letter
if (letters.indexOf(letterKey) === -1) {
letters += letterKey;
groups[letterKey] = [brands[i]];
} else {
groups[letterKey].push([brands[i]]);
}
};
console.log(letters);
let brands = this.props.brands.all_brands
if (brands) brands.sort(this.dynamicSort("name"));
if (brands) len = brands.length
const filteredList = this.filterItems(brands, letters);
return (
<ul>
{filteredList}
</ul>
);
}
注意:我需要帮助将第一个字母映射到标题标记中的列表。
为应用程序网址示例提供更好的视图: https://stackblitz.com/edit/react-pfzlvo
答案 0 :(得分:1)
将您的品牌预处理到地图{letterKey:[brands]}中以用于渲染功能。
const groups = brands.reduce((groups, brand) => {
const letterKey = brand.name.charAt(0).toLowerCase();
(groups[letterKey] || (groups[letterKey] = [])).push(brand);
return groups;
}, {});
将[密钥,品牌]的条目映射到您的无序列表
Object.entries(groups).sort().map(([letterKey, brands]) => (
<div key={letterKey}>
<h4>{letterKey}</h4>
<ul>
{ brands.map(brand => <li key={brand}>{brand}</li>) }
</ul>
</div>
));
const brands = ['cca', 'ccb', 'ccc', 'bba', 'bbb', 'bbc', 'aaa', 'aab', 'aac'];
const groups = brands.reduce((groups, brand) => {
const letterKey = brand.charAt(0).toLowerCase();
(groups[letterKey] || (groups[letterKey] = [])).push(brand);
return groups;
}, {});
Object.entries(groups).sort().map(([letterKey, brands]) => {
console.log('KEY', letterKey);
brands.map(brand => console.log('\tbrand', brand));
});
答案 1 :(得分:0)
将品牌groups = {a: [apple, Ant], b: [Babel, Ball], ...}
分组后,您可以迭代类似的组
Object.keys(groups).sort().map(letter, key => (
<div key={key}>
<h4>{letter}</h4>
<ul>
{
groups[letter].map((word, index) => (
<li key={index}>{word}</li>
))
}
</ul>
</div>
))
答案 2 :(得分:0)
{redirect_uri}#access_token=<<supplied_token>>&token_type=bearer&scope=private+public&expires_in=3600&state=<<givenstate>>