我是新来的反应者。我开始创建一个电话簿应用程序,该应用程序将获取一个json文件,并将其加载到屏幕上。您可以对数据进行排序,过滤,添加,删除,编辑。 我的问题是我无法使代码更整洁,而且看起来真的很糟糕,因为我什至在重复代码块。
import React from 'react';
const filteredAndSorted = ({contacts, search, sortIt, sortBy, direction, deleteContact}) => {
if (direction === 'notsorted') {
const filteredData = contacts.filter(
contacts => {
return contacts.name.toLowerCase().includes(search.toLowerCase()) ||
contacts.address.toLowerCase().includes(search.toLowerCase()) ||
contacts.phone_number.includes(search);
})
return (
<div>
{filteredData.map((contacts) =>
<ul className="gradient_text" key={contacts.name}>
<li>Name: {contacts.name}</li>
<li>Phone: {contacts.phone_number}</li>
<li>Address: {contacts.address}</li>
<li>Id: {contacts.name}</li>
<button onClick={() => deleteContact(contacts.name)}>delete</button>
<hr />
</ul>
)}
</div>
);
}
else if(direction === 'Ascending') {
let filteredAndSortedData =
contacts
.sort((a, b) => { if(a.name < b.name) { return -1; } if(a.name > b.name) { return 1; } return 0; })
.filter(
contacts => {
return contacts.name.toLowerCase().includes(search.toLowerCase()) ||
contacts.address.toLowerCase().includes(search.toLowerCase()) ||
contacts.phone_number.includes(search);
})
return (
<div>
{filteredAndSortedData.map((contacts) =>
<ul className="gradient_text" key={contacts.name}>
<li>Name: {contacts.name}</li>
<li>Phone: {contacts.phone_number}</li>
<li>Address: {contacts.address}</li>
<li>Id: {contacts.name}</li>
<button onClick={() => deleteContact(contacts.name)}>delete</button>
<hr />
</ul>
)}
</div>
);
}
else if(direction === 'Descending') {
let filteredAndSortedData =
contacts
.sort((a, b) => { if(a.name > b.name) { return -1; } if(a.name < b.name) { return 1; } return 0; })
.filter(
contacts => {
return contacts.name.toLowerCase().includes(search.toLowerCase()) ||
contacts.address.toLowerCase().includes(search.toLowerCase()) ||
contacts.phone_number.includes(search);
})
return (
<div>
{filteredAndSortedData.map((contacts) =>
<ul className="gradient_text" key={contacts.name}>
<li>Name: {contacts.name}</li>
<li>Phone: {contacts.phone_number}</li>
<li>Address: {contacts.address}</li>
<li>Id: {contacts.name}</li>
<button onClick={() => deleteContact(contacts.name)}>delete</button>
<hr />
</ul>
)}
</div>
);
}
}
export default filteredAndSorted;
我想将此文件拆分为较小的组件,但是我对访问filterAndSorted并通过它进行映射感到困惑。任何建议都非常感谢。
答案 0 :(得分:1)
更快的建议:在顶部定义一个简单的函数,如下所示:
button
您可以在此处用更简单的形式替换const contactDetail = (contacts) =>
<ul className="gradient_text" key={contacts.name}>
<li>Name: {contacts.name}</li>
<li>Phone: {contacts.phone_number}</li>
<li>Address: {contacts.address}</li>
<li>Id: {contacts.name}</li>
<button onClick={() => deleteContact(contacts.name)}>delete</button>
<hr />
</ul>
)
呼叫:
.map