首页 > 解决方案 > 在 ReactJS 中调用本地 json 文件并解析数据

问题描述

我有以下 json 文件。现在,我将它保存在本地的 ReactJS 项目中。后来计划搬到服务器位置。

abtestconfig.json

[
    { 
        "abtestname": "expAButton",
        "traffic": 1,
        "slices": 
        [
            "orange",
            "blue"
        ]
    },
    { 
        "abtestname": "expTextArea",
        "traffic": 0.5,
        "slices": 
        [
            "lightgrey",
            "yellow"
        ]
    }
]

我想读取和获取数据并解析它并应用到一个函数中。我得到了一些参考示例代码,并尝试使用fetchapi 将 json 文件与以下代码反应。

读完这个 json 文件后,我必须在abtest函数中传递数据,正如你现在看到的那样,它正在发送硬编码值abtest('expAButton', 0.75).slices('orange', 'blue').run(function ()

我有以下疑问,并希望得到您的指导/澄清。

fetch1.使用api读取json文件的方法是否正确?还有其他最好的方法吗?

2.当我使用fetch下面提到的api时,控制台日志显示GET http://localhost:8080/abtesting/abtestconfig.json 404 (Not Found)

app.jsx 文件:

import './abtesting/abtestconfig.json';    

class App extends React.Component {

    constructor() {
        super();

        this.onClick = this.handleClick.bind(this);
        this.onClickNewUser = this.handleNewUser.bind(this);

        this.state = {
            bgColor: '',
            data: []         
        }         
     };
     handleNewUser (event) {
        abtest.clear();
        window.location.reload();
     }

    render() {
        return (
                <Helmet
                />                 
                <p><b>A/B Testing Experience</b></p>

                    <div className="DottedBox">
                        <p><button id = "newUserButton" onClick = {this.onClickNewUser} style={{backgroundColor:"red"}}>Welcome and click here</button></p>

                    </div>
        );

    }

handleClick () {

        abtest('expAButton', 0.75).slices('orange', 'blue').run(function () {
            expAButton.style.backgroundColor = this.slice.name;
        });
}

setStyle (stylecolor) {
        this.setState({
            bgColor: stylecolor
          })
    }

componentDidMount () {

this.handleClick();

        fetch('./abtesting/abtestconfig.json').then(response => {
            console.log(response);
            return response.json();
          }).then(data => {
            // Work with JSON data here
            console.log(data);
          }).catch(err => {
            // Do something for an error here
            console.log("Error Reading data " + err);
          });
    }
}    
export default hot(module)(App);

标签: jsonreactjs

解决方案


推荐阅读