点赞操作:客户端只处理点赞的状态和取消点赞的状态,具体就是点赞后图标变红,下面的点赞数+1,取消点赞时,图标去红,点赞数-1,至于有多少个点赞数,每次请求数据的时候每次都要从后台拉取,具体就是发送post请求。
1.Storage接口的封装:
import React, { Component } from 'react';
import {
AsyncStorage
} from 'react-native';
// 一般更新的操作其实就是对存储的操作进行了业务封装,并没有固定性,这里只处理“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.进入点赞页时要判断本篇文章是否已经点过赞
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,
// 点赞数,由父组件传过来
likesNum:this.props.likes
}
// 存储点赞数据
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
});
}
}
这样基本实现了点赞、取消赞的功能,补充一下,点赞图标高亮切换的时候,兼容性写法:
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}} />
效果图:
like.gif
网友评论