首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据textbox值实时更改当前路径名?反应路由器

如何根据textbox值实时更改当前路径名?反应路由器
EN

Stack Overflow用户
提问于 2021-05-30 20:11:30
回答 1查看 1.6K关注 0票数 0

假设有一条像<base-url>/search这样的路线

该路由的定义如下

代码语言:javascript
复制
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

编辑

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-30 22:08:38

这可能不是最好的答案,但有了所提供的信息和我在此花费的时间,这里就是一个例子,说明如何根据上下文值触发路由更新。

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67765402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档