Javascript 尝试在React JS中按节显示JSON
问题:Javascript 尝试在React JS中按节显示JSON,javascript,arrays,json,reactjs,jsx,Javascript,Arrays,Json,Reactjs,Jsx,问题: [ { "id": 1, "fname": "Amanda", "lname": "Gonzales", "contact": "(31) 9 9580-2530", }, { "id": 2, "fn
[
{
"id": 1,
"fname": "Amanda",
"lname": "Gonzales",
"contact": "(31) 9 9580-2530",
},
{
"id": 2,
"fname": "Astrid",
"lname": "Guzman",
"contact": "(31) 9 9790-2530",
},
{
"id": 3,
"fname": "Aurora",
"lname": "Muñoz",
"contact": "(57) 9 9580-2530",
},
]
class ShowContactsList extends Component {
render() {
const mappedJSON = mockData.map((inputMap, index) => (
<ContactListOneContact
key={index}
lname={inputMap.lname}
fname={inputMap.fname}
fname={inputMap.fname}
contact={inputMap.contact}
/>
));
return (
<div style={{ backgroundColor: 'yellow', width: '80%' }}>
<h1>A</h1>
{mappedJSON}
</div>
)
}
}
这就是应用程序呈现联系人的方式,按联系人的名字字母A、B、C按部分组织。。。到目前为止,我还没有找到一种从a到Z显示它们的方法。无论是改变JSON结构还是在ReactJS中,都没有解决这个问题。每次在JSON中添加更多属性的尝试都会面临一次“扫描”的限制。感谢您的帮助
这是它背后的JSON:
[
{
"id": 1,
"fname": "Amanda",
"lname": "Gonzales",
"contact": "(31) 9 9580-2530",
},
{
"id": 2,
"fname": "Astrid",
"lname": "Guzman",
"contact": "(31) 9 9790-2530",
},
{
"id": 3,
"fname": "Aurora",
"lname": "Muñoz",
"contact": "(57) 9 9580-2530",
},
]
class ShowContactsList extends Component {
render() {
const mappedJSON = mockData.map((inputMap, index) => (
<ContactListOneContact
key={index}
lname={inputMap.lname}
fname={inputMap.fname}
fname={inputMap.fname}
contact={inputMap.contact}
/>
));
return (
<div style={{ backgroundColor: 'yellow', width: '80%' }}>
<h1>A</h1>
{mappedJSON}
</div>
)
}
}
以及React JS:
[
{
"id": 1,
"fname": "Amanda",
"lname": "Gonzales",
"contact": "(31) 9 9580-2530",
},
{
"id": 2,
"fname": "Astrid",
"lname": "Guzman",
"contact": "(31) 9 9790-2530",
},
{
"id": 3,
"fname": "Aurora",
"lname": "Muñoz",
"contact": "(57) 9 9580-2530",
},
]
class ShowContactsList extends Component {
render() {
const mappedJSON = mockData.map((inputMap, index) => (
<ContactListOneContact
key={index}
lname={inputMap.lname}
fname={inputMap.fname}
fname={inputMap.fname}
contact={inputMap.contact}
/>
));
return (
<div style={{ backgroundColor: 'yellow', width: '80%' }}>
<h1>A</h1>
{mappedJSON}
</div>
)
}
}
class ShowContactsList扩展组件{
render(){
const mappedJSON=mockData.map((inputMap,index)=>(
));
返回(
A.
{mappedJSON}
)
}
}
您可以为联系人按字母创建一个组,然后迭代字母,对于每个字母,迭代联系人
导出默认类ShowContactsList扩展组件{
render(){
const groupedByLetter=mockData.reduce((组,联系人)=>{
const letter=contact.fname[0].toUpperCase();
常量组=组[字母]| |[];
推(触)组;
组[字母]=组;
返回组;
}, {});
return Object.entries(groupedByLetter.map)([letter,contacts])=>{
返回(
{字母}
{contacts.map((inputMap,index)=>(
))}
);
});
}
}
每次迭代
mockData
整个组件重新加载程序时,都会出现无休止的循环。尝试console.log(mappedJson)
并查看它返回什么。将此映射函数移动到其他位置,如类函数或最佳重构组件到功能组件。请注意:所选解决方案假定数据已按姓氏进行预排序。如果未排序,则只按结构中显示的姓氏进行分组。要确保已排序,您可以使用: