【发布时间】:2019-07-02 08:54:19
【问题描述】:
我试图在我的反应应用程序中读取 Json 文件,但控制台显示我的 json 文件的 url 是 404。任何人都可以看看我的代码有什么问题
以下是浏览器控制台中显示的错误。当我打开网络选项卡中显示的 json url 时,它会重定向到页面而不是显示 json -
下面是我的代码-
-
import React from 'react';
import Header from './Header';
import Container from './Container'
import Footer from './Footer'
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
products: []
};
}
componentDidMount() {
fetch("../json/results.json",{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(
console.log("--------"),
(result) => {
this.setState({
isLoaded: true,
products: result.Products
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render(){
const { error, isLoaded, products } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return(
<div>
<Header />
<br></br>
<Container />
<ul>
{(products || []).map(item => (
<li key={item.content_id}>
{item.content_id} {item.content_type}
</li>
))}
</ul>
<br></br>
<Footer />
</div>
);
}
}
}
export default App;
我的 Json 如下 -
{
"Products": [
{
"content_id": "1211122910721",
"content_type": "AVG_Product_C"
]
}
【问题讨论】:
-
为什么需要使用fetch来加载本地json?您可以像从库中导入模块一样导入 json
-
@HemadriDasari 仍然是初学者,正在尝试学习 React。我不确定如何在我的 App.js 文件中导入和使用 JSON
-
请分享您的应用组件的文件夹结构和Json文件。否则很难提供帮助
-
@HemadriDasari 这是我的文件夹结构 - ibb.co/pZxkBRv
-
路径看起来绝对正确。您确定收到文件未找到错误吗?