我有一个横向的搜索组件,搜索组件重定向到/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"感谢你的帮助:
发布于 2021-07-22 10:50:52
我使用表单提交更改了查询参数的句柄:
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>
);
发布于 2021-07-22 10:57:51
React.useCallback的依赖值它是查询值,因为这将您的函数记忆为previos值
const search = useCallback(
function() {
let searchName = document.getElementById('query-search').value;
history.replace({
pathname: '/items',
search: `?search=${searchName}`
});
},
[history, value]
);试试看。
https://stackoverflow.com/questions/68461114
复制相似问题