browserHistory.push 不起作用。它只会将您移动到某个位置,但不会更新应用程序状态。您需要更新应用程序状态,这将反映到位置更新中,但不是相反的方向。请记住,在 React 中,数据是第一位的,它的表示,即使是可变的,也不会改变数据。地点也是如此。
为了使重定向单独起作用,我建议将您的组件包装到withRouter higher-order component。
import React, { Component } from 'react';
import { withRouter } from 'react-router';
class MyComponent extends Component {
render() {
return (
<div>
<button
onClick={() => this.props.router.push('/new-location')}>
Click me to go to /new-location
</button>
</div>
);
}
}
但是如果您需要将数据从一个组件传递到另一个组件,而这两个组件不在层次结构中,我会同意 Alomsimoy 并推荐使用 Redux。但是,如果出于某种原因,这不是一个选项,您可以将此数据存储在两个表单的父组件中:
class FormA extends Component {
render() {
return (
<form onSubmit={() => this.props.onSubmit()}>
<input
type="text"
value={this.props.inputA}
onChange={(event) => this.props.handleChangeA(event)} />
</form>
);
}
}
class FormB extends Component {
render() {
return (
<form onSubmit={() => this.props.onSubmit()}>
<input
type="text"
value={this.props.inputB}
onChange={(event) => this.props.handleChangeB(event)} />
</form>
);
}
}
而他们的父母将统治位置和状态更新:
class Forms extends Component {
constructor() {
super();
this.state = {};
}
handleChange(name, value) {
this.setState({
[name]: value
});
}
renderForm() {
const {
params: {
stepId
}
} = this.props;
if (stepId === 'step-a') { // <- will be returned for location /form/step-a
return (
<FormA
inputA={this.state.inputA}
handleChangeA={(event) => this.handleChange('inputA', event.target.value)}
onSubmit={() => this.props.router.push('/form/step-b')} />
);
} else if (stepId === 'step-b') { // <- will be returned for location /form/step-b
return (
<FormB
inputB={this.state.inputB}
handleChangeB={{(event) => this.handleChange('inputA', event.target.value)} />
);
}
}
render() {
const {
children
} = this.props;
console.log(this.state); // track changes
return (
<div>
{this.renderForm()}
<button
onClick={() => this.props.router.push('/new-location')}>
Click me to go to /new-location
</button>
</div>
);
}
}
export default withRouter(Forms);
所以他们的路线看起来像
<Route path="form/:stepId" component={Forms} />