我是React的新手,并尝试为学习目的做一个虚拟项目。这是我的App.js加载广告,我想点击个人广告的名称,以显示每个广告的详细信息,如描述和图片。以下是代码:
App.js
class App extends Component {
constructor(props){
super(props);
this.state = {
advertisements: []
};
}
componentWillMount(){
axios.get('http://localhost:3000/api/v1/advertisements.json')
.then((response) => {
this.setState({advertisements: response.data.data});
})
.catch(function (error) {
console.log(error);
});
}
render() {
let advertisements = this.state.advertisements
return (
<Jumbotron>
<div>
<br/><br/><br/>
{advertisements.map(advertisement =>
<div key={advertisement.id}>
<h1>
<Link className='adName' to = {{pathname: `advertisement/${advertisement.name}`, query: { id: advertisement.id }}}>
{advertisement.name}
</Link>
</h1>
<h4>{advertisement.price}</h4>
</div>
)}
</div>
</Jumbotron>
);
}
}
export default App;
这是我想要加载广告的详细信息。
Advertisement.js
import React, {Component} from 'react';
export default class Advertisement extends Component{
render(){
const {advertisements, location} = this.props;
if (!advertisements.length || !location) {
return (<div>Loading...</div>);
}
const advertisement = advertisements.find(ad => ad.id == location.query.id);
return advertisement?(
<div>
<h1> {advertisement.name} </h1>
<h3> {advertisement.price} </h3>
<h3> {advertisement.description} </h3>
</div>
):(
<div> Error </div>
)
}
}
这是我的Routes.js for Routing。
export default class Routes extends Component{
render(){
return(
<Router>
<div>
<Navbar inverse fixedTop>
<Grid>
<Navbar.Header>
<Navbar.Brand>
<NavLink className= "nav-item" to="/">HamroBazar</NavLink>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<NavLink className = "nav-item" to = "/components/About"> About </NavLink>
</Grid>
</Navbar>
<Route exact path = '/' component={App} />
<Route exact path = '/components/About' component={About} />
</div>
</Router>
);
}
}
目前我被重定向到:“http://localhost:3001/advertisement/Laptop”,空白页面没有错误。