import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Register from './register/register';
import Login from './login/login';
import {
BrowserRouter as Router,
Route,
NavLink
} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()
class App extends React.Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.register = this.register.bind(this);
}
login() {
history.push('/')
}
register() {
history.push('/login')
}
render() {
return (
<Router>
<div>
<button onClick={this.login}>Login</button>
<button onClick={this.register}>register</button>
<Route exact path='/' component={Register} />
<Route path='/login' component={Login} />
</div>
</Router>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
我有两页登录和注册,我想如上所述路由这些页面调用方法。但是网址正在改变,但页面没有加载。我搜索了一些解决方案,我跟着,但它没有工作,请检查代码有什么问题。谢谢
答案 0 :(得分:1)
我认为您忘记将history
绑定到路由器:
<Router history={history}>
...
</Router>
答案 1 :(得分:0)
您可以使用withRouter HOC
将历史记录作为组件的道具,然后您可以使用this.props.history
class App extends React.Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.register = this.register.bind(this);
}
login() {
this.props.history.push('/')
}
register() {
this.props.history.push('/login')
}
render() {
return (
<Router>
<div>
<button onClick={this.login}>Login</button>
<button onClick={this.register}>register</button>
<Route exact path='/' component={Register} />
<Route path='/login' component={Login} />
</div>
</Router>
);
}
}
const App = withRouter(App);
ReactDOM.render(<App />, document.getElementById('root'));
答案 2 :(得分:0)
首先是你错过了绑定操作
<Router history={history}>
...
</Router>
然后确保您的webpack配置文件具有此代码
devServer: {
historyApiFallback: true,
contentBase: './' }
在module.exports模块中。
快乐编码!!!!