我想在反应中修改JSON文件。有没有办法做到这一点?如何使用React修改JSON文件?
我有这个代码,当我点击一个html元素时运行。最后它调用了VoteTracking,这是我实际修改我的json文件的功能。
handleChange(val){
const { voted, score, imgup, imgdown, deviceKey } = this.state;
const { id } = this.props;
var x = this.state.score, vote = val;
var clr;
if (val) clr="#d98832"; else clr = "#3d3dff";
if(!voted) {
x += val;
this.setState({voted: val, score: x, color: clr });
}
else if(Math.abs(voted)){
if (voted == val){
vote = 0;
x -= val;
this.setState({voted: 0, score: x, color: "#6e6e6e"});
}
else {
x += (2* val);
this.setState({score: x, voted: val, color: clr});
}
}
VoteTracking(this.props.id, deviceKey, vote);
}
这是我VoteTracking.js
const VoteTracking = function(ident, deviceKey, vote){
var fs = require('fs');
var m = JSON.parse(fs.readFileSync('VoteList.json').toString());
var containsID = false;
var found = false;
m.forEach(function(p){
if (p.id == ident) {
containsID = true;
for(var i in p.upvotes){
var temp = p.upvotes[i];
if (temp == deviceKey){
p.upvotes.splice(i, 1);
console.log(i)
found = true;
break;
}
}
if (!found){
for(var i in p.downvotes){
var temp = p.downvotes[i];
if (temp == deviceKey){
p.downvotes.splice(i, 1);
break;
}
}
}
switch (vote) {
case 1: {
p.upvotes.push(deviceKey);
break;
}
case -1: {
p.downvotes.push(deviceKey);
break;
}
}
}
});
if (!containsID){
if (vote){
m.push(
{
id: ident,
upvotes: [deviceKey],
downvotes: []
}
);
}
else if (vote == -1){
m.push(
{
id: ident,
upvotes: [],
downvotes: [deviceKey]
}
);
}
}
fs.writeFile('VoteList.json', JSON.stringify(m, null, "\t"));
};
module.exports = VoteTracking;
,如果我使用的节点其中一期工程,但没有任何方法,反应做到这一点?
什么不适用于它? – mmcrae
我认为它应该仍然与反应工作,如果它与节点工作。尝试打印出你的JSON文件,并确保文件路径仍然正确。 –
它说没有找到模块fs,是否必须运行'npm i -S fs' \t \t **编辑** - 即使我安装fs,它仍然表示模块未解决 – Parkicism