React路由配置 菜品列表二維數組渲染 跳轉詳情傳值
import React, { Component } from 'react';
import {Link } from "react-router-dom";
const axios = require('axios');
class Home extends Component {
constructor(props) {
super(props);
this.state = {
list:[],
domain:'http://a.itying.com/'
};
}
requestData=()=>{
var api=this.state.domain+'api/productlist';
axios.get(api)
.then((response)=>{
console.log(response);
this.setState({
list:response.data.result
})
})
.catch(function (error) {
console.log(error);
})
}
componentDidMount(){
this.requestData();
}
render() {
return (
<div className="home">
<div className="list">
{
this.state.list.map((value,key)=>{
return(
<div className="item" key={key}>
<h3 className="item_cate">{value.title}</h3>
<ul className="item_list">
{
value.list.map((v,k)=>{
return(
<li key={k}>
<Link to={`/pcontent/${v._id}`}>
<div className="inner">
<img src={`${this.state.domain}${v.img_url}`} />
<p className="title">{v.title}</p>
<p className="price">{v.price}元</p>
</div>
</Link>
</li>
)
})
}
</ul>
</div>
)
})
}
</div>
</div>
);
}
}
export default Home;
/* react解析html https://reactjs.org/docs/dom-elements.html <div className="p_content" dangerouslySetInnerHTML={{__html: this.state.list.content}}> </div> */ import React, { Component } from 'react'; import {Link } from "react-router-dom"; const axios = require('axios'); class Pcontent extends Component { constructor(props) { super(props); this.state = { list:[], domain:'http://a.itying.com/' }; } requestData(id){ var api=this.state.domain+'api/productcontent?id='+id; axios.get(api) .then((response)=>{ console.log(response); this.setState({ list:response.data.result[0] }) }) .catch(function (error) { console.log(error); }) } componentWillMount(){ //id console.log(this.props.match.params.id) let id=this.props.match.params.id; this.requestData(id); } render() { return ( <div className="pcontent"> <div className="back"> <Link to='/'>返回</Link></div> <div className="p_content"> <div className="p_info"> <img src={`${this.state.domain}${this.state.list.img_url}`} /> <h2>{this.state.list.title}</h2> <p className="price">{this.state.list.price}/份</p> </div> <div className="p_detial"> <h3> 商品詳情 </h3> <div className="p_content" dangerouslySetInnerHTML={{__html: this.state.list.content}}> </div> </div> </div> <footer className="pfooter"> <div className="cart"> <strong>數量:</strong> <div className="cart_num"> <div className="input_left">-</div> <div className="input_center"> <input type="text" readOnly="readonly" value="1" name="num" id="num" /> </div> <div className="input_right">+</div> </div> </div> <button className="addcart">加入購物車</button> </footer> </div> ); } } export default Pcontent;
