我有一个带有搜索栏的主页。当用户搜索时,我运行一个'SEARCH'
动作,该动作搜索数据并使用查询字符串和搜索结果更新商店。然后,将带有查询参数的结果页面推到反应路由器历史记录中,以呈现结果。
我的问题是,如果有人在执行多次搜索后回击,URL将更改为显示不同的查询参数,但实际上不会执行搜索操作并更新商店。
如何确保在几次搜索后按回去将使商店倒带,或者至少执行另一次搜索以更新结果并匹配“路线”中的查询?
import React from 'react';
import { HashRouter, Switch, Route, Redirect } from 'react-router-dom';
import Search from 'Components/Search';
import Results from 'Containers/Results';
export default () => (
<HashRouter>
<Switch>
<Route path="/search" component={Search} />
<Route path="/results/:query" component={Results} />
<Route path="/" exact component={Search} />
<Route render={() => <Redirect to="/" />} />
</Switch>
</HashRouter>
);
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { withRouter } from 'react-router-dom';
const searchActionCreator = (query) => ({
type: 'SEARCH',
query
});
class Search extends React.Component {
constructor(props) {
super(props);
this.input = React.createRef();
this.search = (e) => {
e.preventDefault();
props.search(this.input.current.value);
props.history.push('/results/' + this.input.current.value);
};
}
render() {
return (
<form onSubmit={this.search}>
<input type="text" defaultValue={this.props.query} ref={this.input} />
<button type="submit">Search</button>
</form>
);
}
};
const mapStateToProps = (state) => ({
query: state.search.query
});
const mapDispatchToProps = (dispatch) => bindActionCreators({
search: searchActionCreator
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(Search));
const initialState = {
query: null,
results: []
};
export default (state = initialState, action) => {
switch(action.type) {
case 'SEARCH':
return {
...state,
query: action.query,
results: searchData()
}
case 'CLEAR_SEARCH':
return initialState;
default:
return state
}
};
import React from 'react';
import Header from 'Containers/Header';
import ItemList from './ItemList';
export default (props) => (
<div>
<Header />
<ItemList items={props.results} />
</div>
);