我改进了第二种方法,现在它正在工作。将历史记录导入我的模块(作为局部变量)仍然感觉很笨拙,因此完全绕过了反应树、redux 存储和反应路由器。
但是,它正在工作并且到目前为止没有引起任何错误。所以我们开始...
我将我的历史对象实例化在:
store.js 模块:
import createHistory from 'history/createBrowserHistory';
...
const history = createHistory();
...
export { history , store }
你可以看到出口历史。然后,我将上述历史记录提供给我的路由器(在我的情况下为 ConnectedRouter,因为我使用的是 react-router-redux):
routes.js 模块
import { store , history } from '/imports/client/store';
const MyStoreRouter = () => {
return (
<Provider store={store}>
<ConnectedRouter history={ history }>
<div>
<Switch>
<Route exact path="/" component={Landing}/>
<Route path="/" component={MainApp}/>
</Switch>
</div>
</ConnectedRouter>
</Provider>
);
};
现在是古怪的部分。我将历史记录导入到显示组件中,并使用它来设置侦听器(以声明 history.location 中的更改)并相应地更改状态:
DisplayComponent.js 模块:
import { history } from '/imports/client/store';
....
export default class EventCreationModal extends Component {
constructor() {
super();
this.handleSelect = this.handleSelect.bind(this);
this.state = {
selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
};
history.listen((location,action) => {
this.setState({
selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
})
});
}
handleSelect(key) {
history.push("/Home",{'category':key})
}
render () {
return (
<Tabs activeKey={this.state.selectedCategory} onSelect={this.handleSelect} id="SportOrSocialSelector">
<Tab eventKey={'sports} .../>
<Tab eventKey={'social} .../>
</Tabs>
)
}