如何根据文本框值实时更改当前路径名?反应路由器

How do you change the current path name in real time based on textbox value? react router

假设有一条路线 <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

如果文本框中有多个单词或space,例如'lil red',当前路径会立即渲染到<base-url>/search/lil%20red

我需要使用 React <Link/> 吗?

相关话题How to update the url of a page using an input field?,

编辑

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;
}