我已经尝试了很多教程,到目前为止,我可以显示项目并了解一些 React。
URL结构为
/works/2
查询字符串2存储在pageID
内部
然后,我触发 ajax 调用并过滤数据库,仅使用 .find() 显示该数据
这是 WorksPage.js
文件,它将列出公司的工作组合项目。
import React, { Component } from 'react';
import axios from 'axios';
import './index.css';
class WorksPage extends Component {
constructor(props) {
super(props);
this.state = {itemList: []};
}
componentWillMount(){
const pageID = this.props.match.params.page;
axios.get('/api/works.json').then(function(response){
const result = response.data.find(i => i.id === pageID);
this.setState({ isLoaded: true, itemList: result });
}.bind(this));
}
componentDidMount() {
window.scrollTo(0, 0);
}
render(){
return(
<div className="workListing pageWrapper">
<section className="workListing-process">
<div className="smcontainer center txtc">
{this.state.itemList}
App Type: {this.state.itemList.sub}
App cars: {this.state.itemList.cars.map((car, i) =>
<div key={i}>
{car}
</div>
)}
</div>
</section>
</div>
)
}
}
export default WorksPage;
我的 works.json
的 JSON 是
[{
"id": 0,
"img": "/images/slider.jpg",
"header": "GPS Module",
"sub": "iOS",
"link": "/works/0",
"cars":[ "Ford", "BMW", "Fiat" ]
}{
"id": 1,
"img": "/images/map-slider.jpg",
"header": "GPS Mapping Vectors",
"sub": "iOS",
"link": "/works/1",
"cars":[ ]
},{
"id": 2,
"img": "/images/slider.jpg",
"header": "GPS Module",
"sub": "Android",
"link": "/works/2",
"cars":[ "Ferrari", "BMW", "Land Rover" ]
}]
到目前为止,{this.state.itemList}
返回空白。汽车列表循环也不起作用。如果我在 this.setState
result
的数据
最佳答案
首先不要使用componentWillMount,它都是deprecated并且不用于调用 API。请改用 componentDidMount。
我认为问题是 pageID
是字符串,id
是数字,因此没有匹配。在比较之前尝试将 pageID
转换为数字。
const pageID = parseInt(this.props.match.params.page, 10);
关于javascript - 如何在渲染之前进行 axios 调用并存储 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51942715/