Crud GET:React js axios
Crud GET: React js axios
我目前正在做一个个人项目,我遇到了一个问题我试图使用 reactjs 和 axios 从我的数据库中获取所有汽车数据所以在控制台中我得到了所有这些但在我的页面中没有,它是空白的。知道在服务器端工作。
这是代码:
Component.jsx
constructor(props) {
super(props);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeModel = this.onChangeModel.bind(this);
this.retrieveCars = this.retrieveCars.bind(this);
this.saveCar = this.saveCar.bind(this);
this.newCar = this.newCar.bind(this);
this.state = {
idCars: null,
carName: "",
carModel: "",
cars: [],
submitted: false
};
}
componentDidMount() {
this.retrieveCars();
}
retrieveCars() {
DataService.getAll()
.then(response => {
this.setState({
carsList: response.data
});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
render() {
const { cars } = this.state;
return (
<div >
<h2>List of cars</h2>
<ul className="list-group">
{
cars.map(data => (
<li>
{data.carName}
</li>
))}
</ul>
<button
className="m-3 btn btn-sm btn-danger"
onClick={this.retrieveCars}
>
display All
</button>
DataService.js
getAll() {
return http.get("/get");
}
http.js
export default axios.create({
baseURL: "http://localhost:3000/api",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,PATCH,DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
}
});
请有人指导我解决这个问题
在setState
中使用cars
代替carsList
this.setState({
cars: response.data
});
我目前正在做一个个人项目,我遇到了一个问题我试图使用 reactjs 和 axios 从我的数据库中获取所有汽车数据所以在控制台中我得到了所有这些但在我的页面中没有,它是空白的。知道在服务器端工作。
这是代码:
Component.jsx
constructor(props) {
super(props);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeModel = this.onChangeModel.bind(this);
this.retrieveCars = this.retrieveCars.bind(this);
this.saveCar = this.saveCar.bind(this);
this.newCar = this.newCar.bind(this);
this.state = {
idCars: null,
carName: "",
carModel: "",
cars: [],
submitted: false
};
}
componentDidMount() {
this.retrieveCars();
}
retrieveCars() {
DataService.getAll()
.then(response => {
this.setState({
carsList: response.data
});
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
render() {
const { cars } = this.state;
return (
<div >
<h2>List of cars</h2>
<ul className="list-group">
{
cars.map(data => (
<li>
{data.carName}
</li>
))}
</ul>
<button
className="m-3 btn btn-sm btn-danger"
onClick={this.retrieveCars}
>
display All
</button>
DataService.js
getAll() {
return http.get("/get");
}
http.js
export default axios.create({
baseURL: "http://localhost:3000/api",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,PATCH,DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
}
});
请有人指导我解决这个问题
在setState
cars
代替carsList
this.setState({
cars: response.data
});