React browserHistory.push给出Uncaught TypeError:无法读取未定义的属性'push' [英] React browserHistory.push giving Uncaught TypeError: Cannot read property 'push' of undefined
问题描述
我正在尝试更改点击页面。
这是点击功能
I am trying to change the page on click. Here is the click function
import React, { Component } from 'react';
import {BrowserRouter as Router,Route} from 'react-router-dom';
import { browserHistory } from 'react-router';
class Buttons extends Component {
skipClick(){
browserHistory.push('/sessionstate2');
}
render() {
return (<a className={skipShow} onClick={this.skipClick}>Skip</a>)
}
}
和index.js
import browserHistory from 'react-router';
ReactDOM.render(
<Router history={browserHistory}>
<div>
<Route exact path="/" component={App} />
<Route exact path="/sessionstate1" component={Template1}/>
<Route exact path="/sessionstate2" component={Template2}/>
<Route exact path="/sessionstate3" component={Template3}/>
</div>
</Router>,
document.getElementById('root')
);
给予
Uncaught TypeError:无法读取未定义的属性'push'
Uncaught TypeError: Cannot read property 'push' of undefined
你能告诉我这里我做错了什么吗?
Can you please tell me what am I doing wrong here?
推荐答案
这是一个可重现的例子,说明如何以编程方式更改路由器v4中的路由。
Here's a reproducible example of how to programmatically change routes in react router v4.
首先,为一个简单的应用程序安装样板:
First, install the boilerplate for a simple app:
sudo npm install -g create-react-app
create-react-app demo-app
cd demo-app
npm install react-router-dom
然后我们将 /src/App.js
更改为:
import React from 'react'
import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom'
const BasicExample = () => (
<Router>
<div>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const Button = withRouter(({history}) => (
<button type='button' onClick={() => { history.push('/new-location') }}>Click Me!</button>
))
const About = () => (
<div>
<h2>About</h2>
<Button />
</div>
)
export default BasicExample
然后启动服务器:
npm run start
如果你导航到localhost:3000,然后单击关于,您将看到按钮组件。单击它将以编程方式将路径更改为 / new-location
If you navigate to localhost:3000, then click About, you'll see the button component. Clicking it will programmatically change the route to /new-location
这篇关于React browserHistory.push给出Uncaught TypeError:无法读取未定义的属性'push'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!