我们让Index和List页面以列表的形式传值,点击Index中的列表某项跳转到对应该项的List页面。
设置规则
在AppRouter.js文件中设置List页面根据接收到的参数显示不同内容,接收参数id:
<Route path="/list/:id" component={List}/>
这里规定了List页面必须被传递一个参数id,因此修改一下初始地址,传递一个默认值123:
<li><Link to="/list/123">列表</Link></li>
传递参数
在Index组件的构造函数中初始化state,构造对象列表list,包含cid和title两个属性:
constructor(props) {
super(props);
this.state = {
list: [
{
cid: 123,
title: '我的个人博客-1'
},
{
cid: 456,
title: '我的个人博客-2'
},
{
cid: 789,
title: '我的个人博客-3'
},
]
}
}
利用map循环显示列表信息在Index页面:
render() {
return (
<div>
<div>Juan.com</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index + item}>
{item.title}
</li>
)
})
}
</ul>
</div>
);
}
显示出了列表信息:
在Index.js中引入Link,让每一个列表项传递值到List页面:
import {Link} from 'react-router-dom';
注意地址拼接。
return (
<li key={index + item}>
<Link to={'/list/'+item.cid}>
{item.title}
</Link>
)
此时列表每一项都显示出了链接的效果:
接收参数
在List组件中编写componentDidMount生命周期函数,接收传递过来的值:
/**在该生命周期中接收值 */
componentDidMount(){
console.log(this.props);
let tempId = this.props.match.params.id;
this.setState({
id:tempId
})
}
显示值
编写List组件的render函数,显示接收到的值:
render() {
return (
<h2>List-page-{this.state.id}</h2>
}
实现效果如下:
完整代码如下
AppRouter.js
import React from 'react';
import { BrowserRouter as Router,Route,Link } from 'react-router-dom';
import Index from './Pages/Index';
import List from './Pages/List';
function AppRouter(){
return (
<Router>
<ul>
<li><Link to="/">首页</Link></li>
<li><Link to="/list/123">列表</Link></li>
</ul>
{/* exact表示精确匹配 */}
<Route path="/" exact component={Index}/>
<Route path="/list/:id" component={List}/>
</Router>
)
}
export default AppRouter;
Index.js:
import React, { Component } from 'react';
import {Link} from 'react-router-dom';
class Index extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
cid: 123,
title: '我的个人博客-1'
},
{
cid: 456,
title: '我的个人博客-2'
},
{
cid: 789,
title: '我的个人博客-3'
},
]
}
}
render() {
return (
<div>
<div>Juan.com</div>
<ul>
{
this.state.list.map((item, index) => {
return (
<li key={index + item}>
<Link to={'/list/'+item.cid}>
{item.title}
</Link>
</li>
)
})
}
</ul>
</div>
);
}
}
export default Index;
List.js:
import React, { Component } from 'react';
class List extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return (
<h2>List-page-{this.state.id}</h2>
);
}
/**在该生命周期中接收值 */
componentDidMount(){
console.log(this.props);
let tempId = this.props.match.params.id;
this.setState({
id:tempId
})
}
}
export default List;