假设有一条像<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>还有一个textbox组件,它使用useContext钩子和contextprovider,onChange保存<Search/>组件使用的文本框输入的当前值。
如何将路径名实时更改为搜索输入的名称?如果文本框为空,则默认为<base-url>/search。
例如,如果在文本框中键入'lil‘,当前路由或路径名将同时重定向/呈现到<base-url>/search/lil
如果文本框中有多个单词或空格,如'lil red',当前路径将立即呈现给<base-url>/search/lil%20red。
我需要使用react <Link/>吗?
相关线程How to update the url of a page using an input field?,react-router - how change the 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发布于 2021-05-30 22:08:38
这可能不是最好的答案,但有了所提供的信息和我在此花费的时间,这里就是一个例子,说明如何根据上下文值触发路由更新。
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;
}https://stackoverflow.com/questions/67765402
复制相似问题