(跟风吐槽下react-router,V3到V4,网上很多教程现在大多还是V3的,如果照搬代码,分分钟入坑,对于新手学习还是存在一定阻碍的;But,对于真正的前端高手来说应该不是问题。终极结论:新技术,还得看官网文档)
一、入坑代码
- class UserAdd extends React.Component {
- handleSubmit (e) {
- ...
-
- fetch('http://localhost:3000/user',{ ... })
- .then((res) => res.json())
- .then((res) => {
- if (res.id) {
- alert('添加用户成功');
- (1)this.context.router.push('/user/list');
- ---------------------------------------
- return;
- } else {
- alert('添加失败');
- }
- })
- .catch((err) => console.error(err));
- }
- render () { ... }
- }
-
- // 必须给UserAdd定义一个包含router属性的contextTypes
- // 使得组件中可以通过this.context.router来使用React Router提供的方
-
- (2) UserAdd.contextTypes = {
- router: React.PropTypes.object.isrequired
- };
这个组件要实现的功能是,如果成功添加用户,则跳转到用户列表页,而实现这个功能的代码为(1)(2),但是这个实现方式是V3版本的,所以会报错”TypeError: Cannot read property ‘object’ of undefined”
在V4中要实现这个功能,需要如下修改: 1、引入proptypes模块:import PropTypes from “proptypes” 2、修改(1)处代码:this.context.router.history.push(‘/user/list’) 3、修改(2)处代码: UserAdd.contextTypes = { router: PropTypes.object.isrequired }