我已经尝试了很多教程,到目前为止,我可以显示项目并了解一点 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;
我的 JSONworks.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}
返回空白。汽车列表循环也不起作用。Console.log 将返回result
如果我在之后执行 console.log 的数据this.setState