【发布时间】:2016-06-08 18:31:29
【问题描述】:
所以我想对每篇新闻文章都有一个评分系统。实际上有点像 reddit,您可以在其中对每个帖子进行投票和反对。现在,我可以通过单击按钮动态更改分数。现在,我怎样才能将所有不同的分数动态保存到 localStorage,或者像数据库一样存储它会更好吗?
import React from "react";
import Up from "./UpDown/Up";
import Down from "./UpDown/Down";
export default class Vote extends React.Component {
constructor(){
super();
this.state = {
score: 0,
voted: 0,
imgup: "img/upvote.png",
imgdown: "img/downvote.png",
ident: 0
};
}
saveStorage(key, val) {
localStorage.setItem(key, val);
}
handleChangeUp(){
// ===========================skip this part
const {voted, score, imgup, imgdown, ident} = this.state;
var x = this.state.score;
if (!voted) {
this.setState({voted: 1, score: x+=1, imgup: "img/upvote-clicked.png"});
}
else if(Math.abs(voted)){
if (voted == 1){
this.setState({voted: 0, score: x-=1, imgup: "img/upvote.png"});
}
else if (voted == -1){
this.setState({voted: 1, score: x+=2, imgup: "img/upvote-clicked.png", imgdown: "img/downvote.png"});
}
}
//===============================
x = this.state.score;
this.saveStorage(ident, x);
}
handleChangeDown(){
//================================skip this part
const {voted, score, imgup, imgdown, ident} = this.state;
var x = this.state.score;
if (!voted) {
this.setState({voted: -1, score: x-=1, imgdown: "img/downvote-clicked.png"});
}
else if(Math.abs(voted)){
if (voted == 1){
this.setState({voted: -1, score: x-=2, imgup: "img/upvote.png", imgdown: "img/downvote-clicked.png"});
}
else if (voted == -1){
this.setState({voted: 0, score: x+=1, imgdown: "img/downvote.png"});
}
}
//==============================================
x = this.state.score;
this.saveStorage(ident, x);
}
render(){
const vote = {fontFamily: "'Hack', 'Arial'", fontSize: "13px", textAlign: "center", margin: "auto", marginTop: "0px", marginBottom: "0px", color: "#4d4d4d", fontWeight: "700"};
const pos = {width: "35px", marginLeft: "2px", marginRight: "2px"}
const { score, imgup, imgdown } = this.state;
var { id } = this.props;
return(
<div class="col-xs-2 " style={pos} >
<div class="row ">
<div onClick={this.handleChangeUp.bind(this)} style={{cursor: "pointer"}}>
<Up imgURL = {imgup} />
</div>
<div style={vote}>
{score}
</div>
<div onClick={this.handleChangeDown.bind(this)} style={{cursor: "pointer"}}>
<Down imgURL = {imgdown} />
</div>
</div>
</div>
);
}
}
我现在的问题是我不知道如何将 this.props.id 传递给 handleChangUp 和 handleChangeDown 函数。因此,无论我按哪篇文章,该键始终为 0,因为它是默认值。并且存储的分数会延迟 1 次点击。
因此,当我按下 upvote 时,它会在网站上显示 1,但会存储 0。如果我取消选中该 upvote,它将撤消 upvote 并在网站上显示 0,但会存储 1。
另外,请给我关于代码本身的建议,我知道这完全是一团糟,而且可能有一种更有效的方法来做我正在做的事情。
谢谢
【问题讨论】:
-
当你要使用localStorage时,页面如何知道其他人的投票?此外,例如,当用户清除其浏览历史记录时,localStorage 也会被删除。
-
呵呵,我还没想好……非常感谢您的帮助
标签: javascript reactjs