让我们考虑使用HashRouter的情况
import React from 'react'
import { Tabs, Tab } from 'react-bootstrap';
class UserList extends React.Component{
constructor(props, context) {
super(props, context);
this.state = {
startDate: moment().subtract(7, "days"),
endDate: moment().subtract(1, "days"),
results:[]
}
this.handleStartDateChange =this.handleStartDateChange.bind(this);
this.handleEndDateChange = this.handleEndDateChange.bind(this);
}
handleStartDateChange(date) {
this.setState({
startDate: date
});
}
handleEndDateChange(date) {
this.setState({
endDate: date
});
}
render() {
return (
<div>
<div id="fromDateContainer">
<label>From Date</label>
<DatePicker
selected={this.state.startDate}
onChange={this.handleStartDateChange}
dateFormat="YYYY/MM/DD"
maxDate={moment().subtract(1, "days")}
minDate={moment().subtract(15, "months")}
/>
</div>
<div id="toDateContainer">
<label>To Date</label>
<DatePicker
selected={this.state.endDate}
onChange={this.handleEndDateChange}
dateFormat="YYYY/MM/DD"
maxDate={moment().subtract(1, "days")}
minDate={moment().subtract(15, "months")}
/>
</div>
</div>
);
}
}
class TabbedComponent extends React.Component{
constructor(props, context) {
super(props, context);
this.handleSelect = this.handleSelect.bind(this);
this.state = {
key: 1
};
}
handleSelect(key) {
this.setState({ key });
}
render() {
return (
<Tabs
activeKey={this.state.key}
onSelect={this.handleSelect}
id="controlled-tab-example"
unmountOnExit={true}
className="myCustomClass"
>
<Tab eventKey={1} title="Users List">
<UserList/>
</Tab>
<Tab eventKey={2} title="Projects List">
Tab 2 content
</Tab>
</Tabs>
);
}
}
const App = () => {
return (
<Switch>
<Route exact path='/' component={TabbedComponent} />
<Route exact path='/userActivityDetails/:userID/:startDate/:endDate' component={UserActivityDetails} />
</Switch>
);
}
ReactDOM.render(
<HashRouter>
<App/>
</HashRouter>
,document.getElementById('appContainer')
);
如您所见,我在TabbedComponent的第一个标签中有日期过滤器。当用户在选项卡之间导航时,随着重新渲染组件,过滤器值会丢失。同样,在单击“链接到”后,将用户从UserList路由到UserActivityDetails组件时,过滤器值也会丢失。使用选项卡和路由时如何维护过滤器值? 另外,我还希望与过滤的日期一起共享链接,以便当用户使用路由“ /”访问UserList时,日期过滤器已应用于结果集。
PS:当前未使用Redux存储。