如何使用React修改JSON文件?

时间:2016-06-10 19:01:05

标签: javascript json node.js reactjs

我想在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;

如果我使用了node,哪个有效,但有没有办法做出反应呢?

2 个答案:

答案 0 :(得分:2)

由于您提到单击某个元素以触发文件修改,我假设您的React程序在浏览器中运行。虽然fs是Node运行时的一部分,但出于安全原因,浏览器运行时没有这样的东西,除了一些专有的extensions

作为一种解决方法,React页面可以将JSON文档发送到服务器,该服务器能够存储该文件,或将其下载回客户端计算机。

答案 1 :(得分:0)

浏览器不允许您访问文件系统,因此您无法在应用程序的前端部分使用fs。