San*_*nda 5 javascript reactjs react-router
我试图在 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;
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误
Uncaught TypeError: Cannot read property 'transitionTo' of undefined
在线this.context.router.transitionTo('/home');又名 this.context.router 是未定义的。
this.context 已定义,因此没有问题。
我尝试了以下一些方法:
this.context = context;
Run Code Online (Sandbox Code Playgroud)
static contextTypes: {
history: React.PropTypes.object,
location: React.PropTypes.object,
router: React.PropTypes.func.isRequired
}
Run Code Online (Sandbox Code Playgroud)
ComponentName.contextTypes = {
router: React.PropTypes.func.isRequired
}
Run Code Online (Sandbox Code Playgroud)
this.context.history.transitionTo('/home');
this.context.transitionTo('/home');
this.transitionTo('/home');
Run Code Online (Sandbox Code Playgroud)
事实是 this.context.router 仍未定义,我已经搜索了更多线程(主要是这个:https : //github.com/rackt/react-router/issues/975),但仍然找不到任何东西那对我有用。
注意:我使用的是 ES6 &
"react": "^0.14.0",
"react-router": "^1.0.0-rc3"
Run Code Online (Sandbox Code Playgroud)
Dud*_*ude -1
一种解决方案是在自己的文件中创建历史记录并将其导出,如下所示:
import createHistory from 'history/createHashHistory'
export default createHistory()
Run Code Online (Sandbox Code Playgroud)
然后,当您定义应用程序时,您可以执行以下操作:
import React from 'react'
import { Provider } from 'react-redux'
import { Router } from 'react-router-dom'
import history from '../history'
const Application = (props) => {
return (
<Provider store={props.store}>
<Router history={history}>
...
</Router>
</Provider>
)
}
Run Code Online (Sandbox Code Playgroud)
最后,每当您需要访问任何组件中的历史记录时,只需从导出的同一文件中导入它即可推送下一条路线。请参阅此处的这篇文章了解更多信息。
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |