【发布时间】:2016-09-28 15:21:54
【问题描述】:
我尝试遵循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 会更改,但不会呈现新视图。
似乎人们有similar issues in the past,但这些解决方案也不起作用。
我还尝试了creating a higher order component 并使用顶级组件嵌套路由。但是,在这种情况下,我收到“根路由必须只呈现一个元素”的错误。
如何让表单导航到新视图?
【问题讨论】:
-
页面刷新了吗?您只是在提交处理功能中缺少
event.preventDefault()吗? -
没有页面刷新,也没有
event.preventDefault()。即使有这个调用,它仍然做同样的事情。 -
哦.. 我刚刚注意到你的
path中有一个#,但你没有使用hashHistory。应该是 `const path =/merchant/${merchantId} -
是的,我太傻了。如果您将其发布为答案,我会接受。
标签: reactjs react-router