gpt4 book ai didi

javascript - 将 JSON 数据循环到 ReactJS 中

转载 作者:行者123 更新时间:2023-12-01 02:30:58 28 4
gpt4 key购买 nike

我是 ReactJS 的新手,正在尝试从 JSON 文件中获取数据。我创建了 2 个文件,一个是 products.jsonapp.jsx。我可以在 console.log()

中得到结果
[{…}]
0
:
{title: "Product Title", img: "./p-1.jpg", des: "DES1", rs: 599}
length
:
1
__proto__
:
Array(0)

但它正在 View 中呈现。有时我会遇到未定义的情况,或者数据本身未填充。

这是我的 react 代码。

import React from 'react';
import Request from 'superagent';
import ReactDOM from 'react-dom';

import {
Container,
Col,
Row,
Card
} from 'react-bootstrap';

class App extends React.Component {
render() {
return (
<div className="container">
<Header />
<Content />
<Footer />
</div>
);
}
}

// Header starts
class Header extends React.Component {
componentDidMount() {
//alert('Header');
}
render() {
return (
<header>
<h1>Header !! </h1>
</header>

);
}
}
// Header ends

// Content starts
class Content extends React.Component {
constructor() {
super();
this.state = {
data: []
}
}

componentDidMount() {
var url = "./products.json";
Request.get(url)
.then((res) => {
console.log(res.body.data);
console.log(res.body.data.title);
//this.setState({data: data.conversations});
this.setState({
PTitle: res.body.title,
PImg: res.body.img,
PDesc: res.body.des,
PRs: res.body.rs
});
})
.catch(function (err) {
alert(err);
// err.message, err.response
});

}
render() {
return (
<ul>
{
this.state.data.map((key, i) =>
<ProductList key={i} products={key} />)
}
</ul>
)
}
}
// Content ends

// Footer starts
class Footer extends React.Component {
render() {
return (
<div>
Footer !!
</div>
)
}
}
// Footer ends


// Products Starts
class ProductList extends React.Component {
render() {
return (
2. - <li>{PTitle}</li>
)
}
}
// Products Ends

export default App;

最佳答案

我不熟悉superagent,但它看起来像您的输入./products.json,充当http://localhost:3000/products。 json (假设你在端口 3000 运行 React)

我认为第一步你可以替换serve static json来使用模拟服务器,如https://www.mocky.io/并生成响应

但是如果您可以使用 superagent 提供静态 json,则必须接收数据,然后设置为组件状态。

如果您的请求成功,请设置状态,

// componentDidMount()

let url = 'http://www.mocky.io/v2/5a6032db100000fa02307802';

Request.get(url)
.then((res) => {
this.setState({data: res.body.data});
}).catch(() => {});

并更新您的 render() 方法

return (
<ul>
{
this.state.data.map((product, index) => (
<ProductList key={index} product={product} />
))
}
</ul>
)

最后是 render() 方法中的 ProductList,因为您将 product 作为 props 发送

render() {
const { title, img, des, rd } = this.props.product;

return (
<li>{title} : {des} : {rd} : {img}</li>
)
}

关于javascript - 将 JSON 数据循环到 ReactJS 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48314170/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com