使用的 react-router 2.4.0
import { Link , History} from 'react-router';
//分页点击跳转
onChange (index) {
this.setState({ index });
let Id = this.state.Id;
this.props.history.pushState(null,'list/'+ Id +'/page/'+index);
}
以上是 在点击分页 组件的时候 做 路由跳转
但在浏览器控制台 报错了
browser.js:49Warning: [react-router] `props.history` and `context.history` are deprecated. Please use `context.router`. http://tiny.cc/router-contextchanges
请使用 context.router
这个该怎么用呢
查看官方的 警告地址
按着 文档上说的 使用 this.context.router.push()
以上事件鼠标点击后 就报错了 , 因为 没有 this.context
这个 this.context
需要在哪定义好吗
先把官方关于 context
的文档通读一遍:https://facebook.github.io/react/docs/context.
然后具体到 react-router 的问题其实很简单,在需要用 this.context.router
的组件里声明 contextTypes
就好了。只是具体到代码还要看你用什么方式写 JavaScript 代码的,以下是一个 babel + stage-0 的例子(可以处理 class 内部的静态成员)
然后,正解来了
class ViewDetail extends React.Component {
static contextTypes = {
router: React.PropTypes.object
}
constructor(props) {
super(props);
this.field = new Field(this, { onChange: this.fieldChange.bind(this) });
this.state = {
pageType: '', // 页面状态
};
}
componentDidMount() {}
onChange (index) {
this.setState({ index });
let Id = this.state.Id;
this.context.router.push('list/'+ Id +'/page/'+index);
}
试试看吧