项目场景:
ArticleList组件:通过该列表的路由组件进入文章详情页面,并由该组件中的路由组件传递参数id到文章详情页面
class ArticleList extends Component {
constructor(props) {
super(props);
}
render() {
const { articleList, getMoreList } = this.props;
return (
<Fragment>
{
articleList.map((item, index) => {
return (
<Link to={'/detail/' + item.get('id')} key={index}>
<ListItem >
<ListInfo>
<h3 className="title">{item.get('title')}</h3>
<p className="info">{item.get('info')}</p>
</ListInfo>
{/* <img src="https://upload-images.jianshu.io/upload_images/23868698-07ed2ab2a9c8a6c1.jpg?imageMogr2/auto-orient/strip|imageView2/1/w/360/h/240"></img> */}
</ListItem>
</Link>
)
})
}
<LoadMore onClick={getMoreList.bind(this)}>加载更多</LoadMore>
</Fragment>
)
}
}
Detail组件
class Detail extends Component {
constructor(props) {
super(props);
}
render() {
const { title, content, params } = this.props;
console.log(params.id);
return (
<Bodybackground>
<DetailWrapper>
<Header>{title}</Header>
<Context dangerouslySetInnerHTML={{ __html: content }} />
</DetailWrapper>
</Bodybackground>
)
}
componentDidMount() {
this.props.getDetail();
}
}
问题描述
props中并没有match参数以及其params参数,也取不了路由传递过来的参数
原因分析:
从react-router-dom v6版本开始,路由参数必须使用函数组件进行接收,类组件中无法通过this.props中接收路由组件传递的参数。
解决方案:
将文章详情组件转换成函数组件,利用react-router-dom提供的useParams进行参数的获取。
function Detail(props) {
const { title, content } = props;
const params = useParams();
const { id } = params;
console.log(id);
props.getDetail();
return (
<Bodybackground>
<DetailWrapper>
<Header>{title}</Header>
<Context dangerouslySetInnerHTML={{ __html: content }} />
</DetailWrapper>
</Bodybackground>
)
}
这样就Detail组件就可以接收到路由组件传递过来的参数id了。
遗留问题:
由于使用的是函数组件,函数组件中并没有生命周期函数,这也导致了
props.getDetail();
在每一次页面渲染的时候都要执行一遍,该方法的作用是通过axios获取数据并派发action完成reducer中数据的更新,我们只需要执行一次就行了,在之前的类组件中我使用了
componentDidMount() { this.props.getDetail(); }
这个生命周期函数来实现,而在函数组件中,应该使用React Hooks来完成上述需求,等后面学习了React Hooks再对上述代码进行完善。