點贊操作:客戶端只處理點贊的狀態(tài)和取消點贊的狀態(tài),具體就是點贊后圖標變紅露乏,下面的點贊數(shù)+1碧浊,取消點贊時,圖標去紅瘟仿,點贊數(shù)-1箱锐,至于有多少個點贊數(shù),每次請求數(shù)據(jù)的時候每次都要從后臺拉取劳较,具體就是發(fā)送post請求驹止。
1.Storage接口的封裝:
import React, { Component } from 'react';
import {
AsyncStorage
} from 'react-native';
// 一般更新的操作其實就是對存儲的操作進行了業(yè)務(wù)封裝,并沒有固定性观蜗,這里只處理“string”類型的key值臊恋。
export default class Storage extends Component {
constructor(props){
super(props);
this.state = {}
}
// 增
static save(key,value) {
try {
return AsyncStorage.setItem(key, JSON.stringify(value), ()=>{
console.log("save success with key:value => ",key, value);
});
} catch(e) {
console.log(e);
}
}
// 刪
static remove(key) {
try {
return AsyncStorage.removeItem(key, ()=>{
console.log("remove value for key: ",key);
});
} catch(e) {
console.log(e);
}
}
// 查
static getValueForKey(key) {
try {
return AsyncStorage.getItem(key, ()=>{
console.log("trying to get value with key :", key);
}).then((value)=>{
return JSON.parse(value);
},
(e) => {
console.log(e);
});
} catch(e) {
console.log(e);
}
}
// 取消點贊
static update(key,value){
try {
return AsyncStorage.getItem(key,()=>{
}).then((item) => {
let arry = JSON.parse(item);
let index = arry.indexOf(value);
if (index > -1) {
arry.splice(index, 1);
}
return AsyncStorage.setItem(key, JSON.stringify(arry), ()=>{
console.log("update success with key:value => ",key, arry);
});
})
} catch(e){
}
}
render() {
return null;
}
}
2.進入點贊頁時要判斷本篇文章是否已經(jīng)點過贊
componentDidMount() {
// 獲取本地存儲記錄
Storage.getValueForKey('user_like_history')
.then(historyLikes => {
this.historyLikes = historyLikes ? historyLikes : [];
if(this.historyLikes.includes(this.props.title)){
this.setState({
liked:true
})
}
}).catch(err => {
console.log(err)
})
}
this.historyLikes是在constructor()方法中定義的:
constructor(props){
super(props);
this.state = {
liked:false,
// 點贊數(shù),由父組件傳過來
likesNum:this.props.likes
}
// 存儲點贊數(shù)據(jù)
this.historyLikes = [];
}
3.點贊和取消贊的操作
likeArticle(title){
if(this.state.liked){
this.setState({
liked:false,
likesNum:this.state.likesNum-1
})
// 取消點贊
Storage.update('user_like_history',title);
}else{
// 點贊
this.historyLikes.push(title);
Storage.save('user_like_history',this.historyLikes);
this.setState({
liked:true,
likesNum:this.state.likesNum+1
});
}
}
這樣基本實現(xiàn)了點贊墓捻、取消贊的功能抖仅,補充一下,點贊圖標高亮切換的時候,兼容性寫法:
const img_arr = [require('../img/like_gray.png'),require('../img/like_red.png')];
...
<Image source={this.state.liked ? img_arr[1] : img_arr[0]} style={{width:40,height:40}} />
效果圖: