使用browserhistory更改URL反应路由但没有任何反应

时间:2017-06-02 12:08:50

标签: javascript reactjs react-router

我正在努力让反应路由器工作。这是我的代码:

var hashHistory = require('react-router-dom').hashHistory;
var BrowserRouter = require('react-router-dom').BrowserRouter;
var Route = require('react-router-dom').Route;
var ReactDOM = require('react-dom');
var React = require('react');
var Index = require('./index');
var Login = require('./login');

ReactDOM.render(
    <BrowserRouter history={hashHistory}>
        <div>
            <Route path="/" component={Index} />
            <Route path="/login" component={Login} />
         </div>
    </BrowserRouter>,
    document.getElementById('main-content')
);

然后在我的index.js中我这样做:

 <div className="navbar-nav" onClick={() => this.props.history.push('/login')}>
                    Log in
                </div>

这会将url更改为/ login,但不会呈现登录文件。有什么问题?

2 个答案:

答案 0 :(得分:3)

似乎当您切换到/时,它与<Route path="/" component={Index} /> 匹配:

exact

尝试在路线中添加<Route exact path="/" component={Index} /> 道具,如下所示:

<Route path="/login" component={Login} />
<Route path="/" component={Index} />

您还可以尝试做的是更改匹配顺序:

export class UserEditComponent implements OnInit {

    private user: User;
    private test: String;


    ngOnInit() {
        this.test = 'TEST';
        this.route.params
        .map(params => +params['userId'])
        .switchMap(
            userId => this.userService.getById(userId)
        )
        .subscribe((user: User) => {
            this.user = user;
            this.test = 'TEST';
        });
    }
}

答案 1 :(得分:0)

你的index.js是一个单独的文件或组件吗?如果是这样,您需要使用路由器中间件将其连接到Link

导入withRouter组件并直接使用它, 或绑定一个单击处理程序并包装import React from 'react'; import {Link, withRouter} from 'react-router'; class Test extends React.Component { constructor(props) { super(props); this.handleLink = this.handleLink.bind(this); } handleLink() { this.props.history.push('/login') } render() { return ( <div> <Link to={{pathname: '/login'}}>Link</Link> <button onClick={this.handleLink}>Click</button> </div> ); } } export default withRouter(Test); 以将路由器调用挂载到props。

{{1}}