假设有一条类似<base-url>/search
的路由
路线的定义类似
import { Link, BrowserRouter as Router, Route } from "react-router-dom";
import { useHistory, useLocation } from "react-router-dom";
...
<Router>
...
<Route path="/search/:searchInput">
<Search />
</Route>
</Router>
还有一个文本框组件,它使用useContext
挂钩和上下文提供程序,onChange
保持<Search/>
组件使用的文本框输入的当前值
如何将路径名实时更改为搜索输入的名称?如果文本框为空,则应默认为<base-url>/search
例如,如果在文本框中键入"lil",则当前路由或路径名将同时重定向/呈现到<base-url>/search/lil
如果文本框中有多个单词或空格,例如"lil-red",则当前路径将立即呈现为<base-url>/search/lil%20red
我需要使用react<Link/>
吗?
相关线程如何使用输入字段更新页面的url?,react router-如何更改url
编辑
import SearchContext from "../Search/context"
const Search = () => {
const context = useContext(SearchContext)
// context.searchInput is the value of the textbox provided by context.provider
useEffect(() => {}, [])
return (...)
}
export default Search
这可能不是最好的答案,但根据提供的信息和我在上面花费的时间,这里是一个如何根据上下文值触发路由更新的示例。
import SearchContext from "../Search/context"
import { useHistory, useLocation } from 'react-router-dom';
const Search = () => {
const context = useContext(SearchContext);
const history = useHistory();
const location = useLocation();
// The below use effect will trigger when ever one of the following changes:
// - context.searchInput: When ever the current search value updates.
// - location.pathname: When ever the current route updates.
// - history: This will most likely never change for the lifetime of the app.
useEffect(() => {
let basePath = location.pathname;
// As the available information does not pass a "Base Route" we must calculate it
// from the available information. The current path may already be a search and
// duplicate "/search/" appends could be added with out a small amout of pre-processing.
const searchIndex = basePath.indexOf('/search/');
// Remove previous "/search/" if found.
if (searchIndex >= 0) {
basePath = basePath.substr(0, searchIndex);
}
// Calculate new path.
const newPath = `${basePath}/search/${encodeURI(context.searchInput)}`;
// Check new path is indeed a new path.
// This is to deal with the fact that location.pathname is a dependency of the useEffect
// Changing the route with history.push will update the route causing this useEffect to
// refire. If we continually push the calculated path onto the history even if it is the
// same as the current path we would end up with a loop.
if (newPath !== location.pathname) {
history.push(newPath);
}
}, [context.searchInput, location.pathname, history]);
return null;
}