[英]Sorting Phone Contacts With React Native
我的 react-native 應用程序向擁有我的應用程序的用戶電話簿中的聯系人發送類似於消息的內容。 所以當用戶注冊時,他們只注冊使用我的應用程序,他們只注冊他們的電話號碼。 在向聯系人發送消息時。 我訪問他們的電話簿並將其與我在 Rails 后端中的號碼進行比較。 如果它們匹配用戶電話簿中的號碼。 然后我從他們的電話簿中提取姓名並將其與號碼一起顯示給他們,以便向該聯系人發送消息。
問題是他們是隨機排序的。 我希望他們按字母順序排序。 編號來自 BE(Rails),名稱來自 FE(React-Native)應用程序。 我知道我需要將它們都放入 FE 上的某種數組中,然后對它們進行排序。 不幸的是,我的 Javascript 和 React-Native 技能仍然有些薄弱。 我從理論上知道我需要做什么,但我似乎無法讓它發揮作用。
我當然省略了相當多的代碼,只留下了重要的部分。 第一部分展示了三個函數“parseContacts、fetchContacts、getContactName。
“fetchContacts”從 BE 獲取電話號碼。 “getContactName”從電話電話簿中獲取名稱。 “parseContacts”按照它在罐頭上所說的做。
async parseContacts(contacts) {
let numbers = [];
contacts.forEach(element => {
element.contactNumber = element.phoneNumbers[0] ? element.phoneNumbers[0].number.replace(/[^a-zA-Z0-9]/g, '') : '';
element.phoneNumbers[0] ? numbers.push(element.phoneNumbers[0].number.replace(/[^a-zA-Z0-9]/g, '')) : null;
});
this.setState({ phoneContacts: contacts })
return numbers;
}
async fetchContacts(contacts) {
let phoneNumbers = await this.parseContacts(contacts);
if (phoneNumbers.length) {
this.setState({ isLoadingNumbers: true })
let data = {
"numbers": phoneNumbers,
}
try {
let res = await postFunctionWithAuthToken(`${baseUrl}/contact/check`,
JSON.stringify(data), this.state.authToken);
if (res.response) {
console.log('contacssssst: ', res.contact_list);
this.setState({ contacts: res.contact_list, isLoadingNumbers: false })
} else {
this.setState({ isLoadingNumbers: false })
Alert.alert('Error', `${res.error}! try again.`);
}
} catch (error) {
console.log('error: ', error);
this.setState({ isLoadingNumbers: false })
Alert.alert('Error', 'request failed! try again.')
}
}
}
getContactName(number) {
const { phoneContacts, countryCode } = this.state;
if (phoneContacts.length) {
let index = phoneContacts.findIndex(element => {
let parsedNumber = element.phoneNumbers[0] ? element.phoneNumbers[0].number.replace(/[^a-zA-Z0-9]/g, '') : "";
if (parsedNumber) {
if (parsedNumber.slice(0, 1) === "0") {
if (parsedNumber.slice(1, 2) === "0") {
if (parsedNumber.substring(2) === number ||
parsedNumber.substring(2).replace(`${countryCode}0`, countryCode) === number) {
return number;
}
} else {
return countryCode + parsedNumber.substring(1) === number;
}
} else {
// console.log('nummm: ', parsedNumber, number);
// return parsedNumber === number;
if (parsedNumber === number ||
parsedNumber.replace(`${countryCode}0`, countryCode) === number) {
return number;
}
}
}
});
if (Platform.OS === 'ios') {
return index >= 0 ? phoneContacts[index].givenName : ''
} else {
return index >= 0 ? phoneContacts[index].displayName : ''
}
}
}
下面的代碼是我在列表中呈現手機上的姓名和號碼的地方。
<View style={styles.container}>
{this.state.contacts.length ?
<FlatList
data={this.state.contacts}
extraData={this.state}
numColumns={1}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View style={styles.itemContainer}>
<View>
<Text style={{ color: '#000', fontSize: 20 }}>
{this.getContactName(item.phone_number)}</Text>
<Text style={{ color: '#000' }}>
{item.phone_number}</Text>
</View>
{item.selected ?
<TouchableOpacity onPress={() => this.removeContact(item)}>
<Icon name={"ios-add-circle"} size={26} color={primaryColor} />
</TouchableOpacity>
:
<TouchableOpacity onPress={() => this.selectContact(item)}>
<Icon name={"ios-add-circle"} size={26} color={'grey'} />
</TouchableOpacity>
}
</View>
)}
/>
希望到目前為止我所做的一切都很清楚。 無論如何,我現在需要什么。 是另一個功能,可以將名稱和數字放在一起並在渲染它們之前對它們進行排序。 至少我是這么認為的。 也許排序需要在渲染中完成。 我不是 100%。 這兩天我一直在嘗試各種方法,但似乎無法按字母順序對聯系人列表進行排序。 任何和所有的幫助都將不勝感激。
您需要將姓名放入 phoneNumbers 數組中,然后進行排序...目前您在呈現電話號碼時獲取聯系人的姓名,因此無法事先進行排序...
if (res.response) {
console.log('contacssssst: ', res.contact_list);
const contacts = res.contact_list.map((contact)=>{
//Loop through the contacts and add the display name found.
contact.displayName = this.getContactName(contact.phone_number);
return contact;
});
//Sort using the displayName property.
contacts.sort((a,b)=>{
if(a.displayName > b.displayName){
return 1;
}
if(a.displayName < b.displayName){
return -1;
}
return 0;
});
this.setState({ contacts: res.contact_list, isLoadingNumbers: false })
}
然后在您的視圖中您可以直接訪問 item.displayName。
我已經很快地編寫了排序函數,不太確定它是否會正確排序。
@salketer 讓我非常接近正確的答案。 我結束了使用不同的排序方式。 還有最后一個 setState 我只需要設置聯系人。 再次感謝。
if (res.response) {
console.log('contacts: ', res.contact_list);
const contacts = res.contact_list.map((contact)=>{
contact.displayName = this.getContactName(contact.phone_number);
return contact;
});
contacts.sort((a, b) => a.displayName.localeCompare(b.displayName));
console.log('contacts_returned: ', contacts);
this.setState({ contacts, isLoadingNumbers: false })
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.