我正在尝试实现一个搜索栏,当用户开始键入内容时,会将用户移动到一个新视图,该视图显示该视图上的结果。
I have the following code which lets the user start searching, sets the searchInput
into a state and moves the user to a new view.
问题是:我无法从SearchBar组件传递和访问searchInput状态到SearchResultsView组件。
SearchBar.tsx
import * as React from 'react'
import { useState } from 'react';
import { useHistory } from 'react-router-dom';
export const SearchBar = () => {
const [searchInput, setSearchInput] = useState('');
const history = useHistory();
const handleInputChange = (value: string) => {
setSearchInput(value);
history.push('/search-results', { searchInput: searchInput });
}
return (
<input
type="text"
value={searchInput}
onChange={(e) => handleInputChange(e.target.value)}
/>
)
}
这是SearchResultsView,我只想访问searchInput查询(然后我可以继续构建搜索逻辑)
import * as React from 'react'
export const SearchResultsView = (searchInput) => {
// What I've tried that didn't work
const query = searchInput // returns empty
const state = useState('searchInput') // returns empty
return (
<div>
{/* Searching for: {searchInput} */}
</div>
)
}
For additional info, here's how I setup the search-results
route
export const App = () => {
return (
<HashRouter>
<div>
<AppSidebar/>
<Switch>
<Route path="/" exact render={() => <MainView/>}/>
<Route path="/search-results" exact render={() => <SearchResultsView/>}/>
</Switch>
</div>
</div>
</HashRouter>
)
}
With
history.push
, you are trying to passsearchInput
as state. Which can be accessed in the other component aslocation.state
. But do note thatsearchInput
is not set at the time you are passing it because setting state is an asynchronous process.If you want to set this from the state, you could use a
useEffect
for this purpose.在这两种情况下,都可以使用以下命令进行访问:
如果希望用户使用参数链接到搜索页面,则可以使用查询参数。