【问题标题】:Bad replace url with query params react router 5.2错误的用查询参数替换 url 反应路由器 5.2
【发布时间】:2021-09-28 08:01:29
【问题描述】:

我有一个横向的搜索组件,搜索组件重定向到 /items?search=:search,:search 是组件输入的内容。我第一次使用搜索组件时它可以工作,但是当我尝试在 /items?search:search 中使用这个组件时,它会重定向到 /items?search=null。

有问题的组件是:

import { useCallback } from 'react';
import { useHistory, useLocation } from "react-router-dom";

// Hook function from https://reactrouter.com/web/example/query-parameters
// A custom hook that builds on useLocation to parse
// the query string for you.
function useQuery() {
  return new URLSearchParams(useLocation().search);
}

/**
 * 
 * @returns 
 */
export function HeaderComponent() {
  let history = useHistory();
  let query = useQuery();
  let value = query.get('search') != null 
    ? query.get('search') 
    : '';

  // Search callback.
  const search = useCallback(
    function() {
      let searchName = document.getElementById('query-search').value;
      history.replace({
        pathname: '/items',
        search: `?search=${searchName}`
      });
    },
    [history]
  );

  return (
    <header>
      <div className="container">
        <img src="">
        </img>
        <form className="">
          <fieldset>
            <input id="query-search" 
              type="text" 
              defaultValue={ value } />
            <button onClick={ search }></button>
          </fieldset>
        </form>
      </div>
    </header>
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

项目的依赖是:

"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"node-sass": "^6.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"

感谢您的帮助:D

【问题讨论】:

    标签: javascript reactjs redirect react-router react-hooks


    【解决方案1】:

    我使用表单提交更改查询参数的句柄:

    const [search, updateSearch] = useState('');
    
    // Set search value.
    const setSearch = (e) => {
      updateSearch(e.target.value);
    }
    
    // Handle form submit, redirect to search item.
    const formSubmit = () => {
      history.push({
        pathname: '/items',
        search: `?search=${encodeURI(search)}`
      });
    }
    
    // Functional component return
    return (
      <header>
        <div className="container">
          <Link to="/">
            <img src={ logo } >
            </img>
          </Link>
          <form onSubmit={ formSubmit }>
            <fieldset>
              <input id="query-search" 
                type="text" 
                defaultValue={ value }
                onChange={ setSearch }
                name="search" />
              <button></button>
            </fieldset>
          </form>
        </div>
      </header>
    );

    【讨论】:

      【解决方案2】:

      你的 React.useCallback 的依赖值是查询值,因为这将你的函数记忆到 previos 值

      const search = useCallback(
          function() {
            let searchName = document.getElementById('query-search').value;
            history.replace({
              pathname: '/items',
              search: `?search=${searchName}`
            });
          },
          [history, value]
        );
      

      试试看。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2018-06-09
        • 2021-10-29
        • 2021-03-17
        • 2021-06-15
        • 1970-01-01
        相关资源
        最近更新 更多