我尝试遵循 this question 中的解决方案并在 react-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 会发生变化,但新 View 不会呈现。
人们似乎有 similar issues in the past ,但这些解决方案也不起作用。
我也尝试过creating a higher order component并将路由与顶级组件嵌套。然而,在这种情况下,我收到错误“根路由必须恰好渲染一个元素。”
如何让表单导航到新 View ?
最佳答案
您的 path
变量中有一个错误的 #
,可能是使用 hashHistory
留下的。忽略它,应该可以工作:
const path = `/merchant/${merchantId}`
关于reactjs - React-router browserHistory.push 不导航到新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37531707/