您好,我是React的新手,我不知道如何使用react和如何将响应数据馈送到我的组件向api发送请求
shop.jsx
import React from 'react';
import './shop.css';
class Shop extends React.Component{
render(){
return(
<div class="blog-post">
<div class="blog-post_img">
<img src="shop.jpg" alt=""></img>
</div>
<div class="blog-post_info">
<h1 class="blog-post_title">{this.props.name}</h1>
<p class="blog-post_text">
{this.props.address}
</p>
<p class="blog-post_text">
{this.props.mobile}
</p>
<a href="#" class="blog-post_cta">Visit Shop</a>
</div>
</div>
);
}
}
export default Shop;
shops.jsx
import React from 'react';
import './shops.css';
import Shop from './shop'
class Shops extends React.Component{
constructor() {
super()
}
componentWillMount() {
this.getData()
}
getData() {
// create a new XMLHttpRequest
var xhr = new XMLHttpRequest()
// get a callback when the server responds
xhr.addEventListener('load', () => {
// update the state of the component with the result here
console.log(xhr.responseText)
})
// open the request with the verb and the url
xhr.open('GET','http://localhost:5000/api/shops/allShops')
// send the request
xhr.send()
}
render(){
const shopjsx = this.state.shops.map((item, i) =>(<Shop name={item.shopname} address={item.address} mobile={item.phoneNumber}/>));
return(
<div id="container">
{shopjsx}
</div>
);
}
}
export default Shops;
我知道我的shop.jsx代码是错误的,我想要的是,我想向我的api发出请求,并希望当我从api获取数据时,我需要将该数据放入在shop.jsx组件中
对api的请求应这样发送: GET http:// localhost:5000 / api / shops / allShops 授权:Bearer dcbjdsbchjedjcvdfcvfcjdfvcjfdjcvfdjcjdfjchjdfchbdfcjhdfhcbj
从响应中我只需要:商店名称,电话号码,地址
我的api响应如下:
fetchedShops: Array(78)
0:
created_at: "2020-06-18T07:50:42.356Z"
isActive: true
isApproved: false
isOpen: true
isPhoneVerified: false
name: "kalluHalwai"
phoneNumber: "9829648597"
plans: []
timingRules: {lunchCancellationDeadline: 1030, dinnerCancellationDeadline: 1730}
updated_at: "2020-06-18T07:50:42.356Z"
__v: 0
_id: "5eeb1cd295c9523da0a99ee0"
__proto__: Object
1:
created_at: "2020-06-18T09:30:28.985Z"
isActive: true
isApproved: false
isOpen: true
isPhoneVerified: false
name: "kalluHalwai"
phoneNumber: "9829648597"
plans: []
timingRules: {lunchCancellationDeadline: 1030, dinnerCancellationDeadline: 1730}
updated_at: "2020-06-18T09:30:28.985Z"
__v: 0
_id: "5eeb3434e2662738509ebf8a"
__proto__: Object
答案 0 :(得分:0)
要使代码正常工作,需要进行一些更改:
this.state
。此属性将存储来自API的数据并在渲染期间使用componentDidMount
代替componentWillMount
。 componentDidMount
方法在首次渲染组件之后运行。这是添加请求第三方数据的好地方。fetch
而不是XMLHttpRequest
从API获取数据。它使代码更清晰,更易于使用。这是工作示例:
class Shops extends React.Component {
constructor(props) {
super(props);
this.state = {
shops: []
};
}
componentDidMount() {
// replace with correct token and URL: http://localhost:5000/api/shops/allShops
const TOKEN = "";
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "get",
headers: new Headers({
Authorization: `Bearer ${TOKEN}`
})
})
.then(response => response.status === 200 ? response.json() : [])
.then(data => this.setState({ shops: data }))
.catch(err => console.log("Error", err));
}
render() {
const shops =
this.state.shops.length > 0 ?
this.state.shops.map(item => (
<Shop name={item.id} address={item.title} mobile={item.body} />
))
: <span>No data</span>;
return <div id="container">{shops}</div>;
}
}
class Shop extends React.Component {
render() {
return (
<div class="blog-post">
<div class="blog-post_img">
<img src="shop.jpg" alt="" />
</div>
<div class="blog-post_info">
<h1 class="blog-post_title">{this.props.name}</h1>
<p class="blog-post_text">{this.props.address}</p>
<p class="blog-post_text">{this.props.mobile}</p>
<a href="https://google.com" class="blog-post_cta">
Visit Shop
</a>
</div>
</div>
);
}
}
ReactDOM.render(<Shops />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
它请求publicly available API,因此数据不同,并且不需要令牌(我添加了设置Authorization
标头,但API并未使用它)。