首页 > react-router 2.4.0 js 点击事件 跳转

react-router 2.4.0 js 点击事件 跳转

使用的 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.route

以下代码

 this.context.route('list/'+ Id +'/page/'+index); 

以上事件鼠标点击后 就报错了 , 因为 没有 this.context
这个 this.context 需要在哪定义好吗

求 React-router 大神指导一下 这个 js 路由跳转该如何破


先把官方关于 context 的文档通读一遍:https://facebook.github.io/react/docs/context.html

然后具体到 react-router 的问题其实很简单,在需要用 this.context.router 的组件里声明 contextTypes 就好了。只是具体到代码还要看你用什么方式写 JavaScript 代码的,以下是一个 babel + stage-0 的例子(可以处理 class 内部的静态成员)

class MyComponent extends React.Component {
    static contextTypes = {
        router: PropTypes.routerShape // comes from `react-router/modules/PropTypes`
    };
    
    // ...
}

但是由于你用的是 v2.4,所以更应该看这里:https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.4.0.md

由于 context 并不是一个稳定的特性(stable feature),所以 v2.4 之后 react-router 提供了一个高阶函数来注入 router 对象,具体的写法在上面的链接里有。需要注意的是,这个新的写法并不代表 context.router 被废弃了,目前的状况是两者并存且等价,任选一种方式皆可。

【热门文章】
【热门文章】