An *_*ser 1 json fetch reactjs
我正在尝试在我的 React 应用程序中读取 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;
Run Code Online (Sandbox Code Playgroud)
我的 Json 如下 -
{
"Products": [
{
"content_id": "1211122910721",
"content_type": "AVG_Product_C"
]
}
Run Code Online (Sandbox Code Playgroud)
由于 JSON 文件已经在 React 应用程序中,因此您可以直接导入它。您可以使用 fetch 从其他服务器/API 获取 JSON/XML 响应
import React from "react";
import Header from "./Header";
import Container from "./Container";
import Footer from "./Footer";
import JSONResult from '../json/results.json';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
products: JSONResult.Products || []
};
}
render() {
const { products } = this.state;
return (
<div>
<Header />
<br />
<Container />
<ul>
{products.map(product => (
<li key={product.content_id}>
{product.content_id} {product.content_type}
</li>
))}
</ul>
<br />
<Footer />
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4598 次 |
| 最近记录: |