【发布时间】:2016-01-17 19:59:20
【问题描述】:
我正在尝试在 n 秒后自动更改路径。 (不使用 <Link to="/home">Home</Link> )。
我的代码如下所示:
class ComponentName extends Component {
constructor (props, context) {
super(props, context);
}
componentDidMount () {
setTimeout(function(){
this.context.router.transitionTo('/home');
}.bind(this), 3000)
}
render() {return (<div>..will go to the home page</div>)}
}
ComponentName.contextTypes = {
router: function () {
return React.PropTypes.func.isRequired;
}
};
export default ComponentName;
这是我遇到的错误
Uncaught TypeError: Cannot read property 'transitionTo' of undefined
在线this.context.router.transitionTo('/home'); aka this.context.router 未定义。
this.context 已定义,所以没有问题。
我尝试了以下一些方法:
this.context = context;
static contextTypes: {
history: React.PropTypes.object,
location: React.PropTypes.object,
router: React.PropTypes.func.isRequired
}
ComponentName.contextTypes = {
router: React.PropTypes.func.isRequired
}
this.context.history.transitionTo('/home');
this.context.transitionTo('/home');
this.transitionTo('/home');
事实是 this.context.router 仍然未定义,我已经搜索了更多的线程(主要是这个:https://github.com/rackt/react-router/issues/975),但仍然找不到适合我的东西。
注意:我使用的是 ES6 &
"react": "^0.14.0",
"react-router": "^1.0.0-rc3"
【问题讨论】:
标签: javascript reactjs react-router