我尝试在我的应用程序中使用 react router v5 集成一个搜索页面。
如何使用我的搜索框更新我的 url 查询参数?
当我刷新应用程序时,我会丢失搜索结果和搜索字段的值。
我使用 redux 来管理我的搜索字段和我的搜索结果的值的状态,我认为通过 url 的参数将是一个更好的解决方案,但我不知道该怎么做。
我尝试了一个解决方案(见我的代码),但是url的查询参数与我的文本字段的值不同步
编辑:
我的组件 Routes.js
const Routes = (props) => {
return (
<div>
<Route exact path="/" component={Home} />
<Route
exact
path='/search'
component={() => <Search query={props.text} />}
/>
<Route path="/film/:id" component={MovieDetail} />
<Route path="/FavorisList" component={WatchList} />
<Route path="/search/:search" component={Search} />
<Route path="*" component={NotFound} />
</div>
)}
我的组件SearchBar.js(内嵌在导航栏中,Search路由显示搜索结果)
编辑:
我想实现Netflix用于系列研究的方法。
我希望无论我在哪个页面都能够进行搜索,如果输入字段中有条目,我会search
使用this.props.history.push (`` search /
)导航到该页面,如果输入字段为空,我会使用this.props.history.goBack ()
.
状态 inputChange 是一个标志,可防止我每次输入字符时都推送到搜索页面。
要了解更多,我已经打开了 = 在这里发帖 =>如何根据字段的值更改路由
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue:'',
};
}
setParams({ query }) {
const searchParams = new URLSearchParams();
searchParams.set("query", query || "");
return searchParams.toString();
}
handleChange = (event) => {
const query = event.target.value
this.setState({ inputValue: event.target.value})
if (event.target.value === '') {
this.props.history.goBack()
this.setState({ initialChange: true })
return;
}
if(event.target.value.length && this.state.initialChange){
this.setState({
initialChange:false
}, ()=> {
const url = this.setParams({ query: query });
this.props.history.push(`/search?${url}`)
this.search(query)
})
}
}
search = (query) => {
//search results retrieved with redux
this.props.applyInitialResult(query, 1)
}
render() {
return (
<div>
<input
type="text"
value={this.state.inputValue}
placeholder="Search movie..."
className={style.field}
onChange={this.handleChange.bind(this)}
/>
</div>
);
}
export default SearchBar;
组件 App.js
class App extends React.Component {
render(){
return (
<div>
<BrowserRouter>
<NavBar />
<Routes/>
</BrowserRouter>
</div>
);
}
}
export default App;
查询搜索结果(使用 Redux 管理)
export function applyInitialResult(query, page){
return function(dispatch){
getFilmsFromApiWithSearchedText(query, page).then(data => {
if(page === 1){
dispatch({
type:AT_SEARCH_MOVIE.SETRESULT,
query:query,
payload:data,
})
}
})
}
}