react-router browserHistory.push没有导航到新页面

时间:2016-05-30 18:23:45

标签: reactjs react-router

我尝试按照this questionreact-router example中的解决方案,但我仍然遇到问题。

我使用的是react-router版本2.4.1,React版本15.1.0和webpack 1.13.1。

我有一个像这样设置的路由器:

import React from 'react';
import {render} from 'react-dom';
import {Router, Route, Link, browserHistory} from 'react-router';
import Component from './component';
import Merchant from './merchant';
import CreateMerchant from './create-merchant';
require('bootstrap/dist/css/bootstrap.css');
// /* globals document, window */
//
// const { pathname, search, hash } = window.location
// const location = `${pathname}${search}${hash}`

render((
    <Router history={browserHistory}>
        <Route path="/" component={Component}/>
        <Route path="/merchant" component={CreateMerchant}/>
        <Route path="/merchant/:merchantId" component={Merchant}/>
    </Router>
), document.getElementById("app"))

当我转到http://localhost:8080/时,我看到了预期的组件:

import React from 'react';
import {Link, browserHistory} from 'react-router';

export default class Component extends React.Component {
    handleSubmit(event) {
        const merchantId = event.target.elements[1].value;

        console.log("Merchant id is " + merchantId);

        const path = `/#/merchant/${merchantId}`;

        browserHistory.push(path);
    }


    render() {
        return <div className="container">
            <h1>Welcome to VPager!</h1>
            <h2>Would you like to create a merchant?</h2>
            <div className="row">
                <div className="col-md-6">
                    <Link className="btn btn-primary" to="/merchant">Yes, create a merchant and start taking
                        customers.</Link>
                </div>
            </div>

            <h2>Or do you have an existing merchant?</h2>
            <form onSubmit={this.handleSubmit.bind(this)}>
                <div className="row">
                    <div className="col-md-3">
                        <button type="submit" className="btn btn-primary">I have an
                            existing merchant ID, and it is:</button>
                    </div>
                    <div className="col-md-2"><input id="merchantId" className="form-control" type="number" /></div>
                </div>
            </form>
        </div>
    }
}

但是,当我单击第二个按钮时,地址栏中的URL会更改,但不会呈现新视图。

似乎人们有similar issues in the past,但这些解决方案也没有。

我还尝试了creating a higher order component并使用顶级组件嵌套路由。但是,在这种情况下,我得到错误&#34;根路由必须正好呈现一个元素。&#34;

如何让表单导航到新视图?

1 个答案:

答案 0 :(得分:3)

您的#变量中存在错误的path,可能会因使用hashHistory而遗留下来。把它拿出来,应该工作:

const path = `/merchant/${merchantId}`