【发布时间】:2018-10-28 07:28:11
【问题描述】:
我正在将 React 和 Redux 用于搜索应用程序。使用react-router-dom,我将/search/:term? 路由到Search 组件:
<Router>
<Switch>
<Route exact path="/search/:term?" component={Search} />
<Redirect to="/search" />
</Switch>
const Search = (props) => {
const { term } = props.match.params;
return (
<div>
<SearchForm term={term}/>
<SearchResults />
</div>
)
};
当用户在SearchForm 组件中提交搜索时,我正在调度一个操作来提交搜索查询。如果给出了一个术语,我也会在构造函数中启动搜索,最初:
class SearchForm extends Component {
constructor(props) {
super(props);
const term = props.term ? props.term : '';
this.state = {
term: term,
}
if (term) {
this.props.submitSearch(term);
}
}
handleSubmit = (e) => {
e.preventDefault();
if (this.state.term) {
this.props.submitSearch(this.state.term);
}
}
render = () => {
<form
onSubmit={this.handleSubmit.bind(this)}>
...
</form>
}
}
我正在使用来自react-router-dom 的withRouter,因此在提交搜索时 URL 会更新。
当用户在浏览器中导航返回时会出现问题。 URL 导航返回,props 更新(即props.match.params.term),但搜索没有重新提交。这是因为 submitSearch 操作仅在 SearchForm.constructor(如果 URL 中有术语,则搜索初始加载)和 SearchForm.handleSubmit 中调度。
当 URL 更改时侦听状态更改为 term 的最佳方法是什么,然后分派搜索操作?
【问题讨论】:
标签: reactjs redux react-redux redux-thunk react-router-dom