react route using browserhistory changes url but nothing happens

[亡魂溺海] 提交于 2021-02-09 08:44:49

问题


I'm trying to get a react router to work. This is my code:

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')
);

and then later in my index.js i do this:

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

This makes the url change to /login but it doesn't render the login file. What is wrong?


回答1:


It seems like when you switch to /login it matches to /:

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

Try to add exact prop to the route, like this:

<Route exact path="/" component={Index} />

What you can also try to do is to change the matching order:

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



回答2:


Is your index.js a separate file or component? If so you need to use the router middleware to connect it to react-router.

Either import the Link component and use it directly, or bind a click handler and wrap withRouter to mount the router calls to the props.

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);


来源:https://stackoverflow.com/questions/44328600/react-route-using-browserhistory-changes-url-but-nothing-happens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!