json - 在 ReactJS 中调用本地 json 文件并解析数据
问题描述
我有以下 json 文件。现在,我将它保存在本地的 ReactJS 项目中。后来计划搬到服务器位置。
abtestconfig.json
[
{
"abtestname": "expAButton",
"traffic": 1,
"slices":
[
"orange",
"blue"
]
},
{
"abtestname": "expTextArea",
"traffic": 0.5,
"slices":
[
"lightgrey",
"yellow"
]
}
]
我想读取和获取数据并解析它并应用到一个函数中。我得到了一些参考示例代码,并尝试使用fetch
api 将 json 文件与以下代码反应。
读完这个 json 文件后,我必须在abtest
函数中传递数据,正如你现在看到的那样,它正在发送硬编码值abtest('expAButton', 0.75).slices('orange', 'blue').run(function ()
我有以下疑问,并希望得到您的指导/澄清。
fetch
1.使用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);
解决方案
推荐阅读
- python - 当我测试 api 它显示方法不允许错误
- android - 如何在 kotlin 中将保留注释与 RetentionPolicy 一起使用
- ssh - 从 gcloud 到 NAT 路由器后面的笔记本电脑的 SSH 端口转发
- java - Apache POI:获取额外的列数和行数
- javascript - 如果javascript中的值不为null,如何添加到查询参数
- c - 将内存分配给可变长度的数组
- python - Python列表索引方法在类中表现得很奇怪
- solr - df 有多个现场支持?
- python - Chromedriver 无法识别选项
- python - 有没有办法在启动 python 控制台后最小化它?