当用户要搜索产品时,我正在尝试创建搜索栏。
这是我的搜索输入:
const [searchTerm, setSearchTerm] = useState("");
const onSubmit = (e) => {
e.preventDefault();
navigate(`/search/${searchTerm}`);
setIsShowing(false);
setOpacity(1);
};
<FormSearch onSubmit={onSubmit}>
<SearchInput type="text"
placeholder="Type something to search"
onChange={(e)=> setSearchTerm(e.target.value)}
defaultValue={searchTerm} />
<SearchButton type="submit" value="Search" />
</FormSearch>
这是单击搜索并将用户带到另一个页面时的路由器:
<Router>
<SearchInfo
path="/search/:title "
searchTerm={searchTerm}
/>
</Router>
这是我搜索后页面的反应功能:
import React, { useEffect, useState } from "react";
import styled from "styled-components";
const SearchInfo = (props) => {
const [products, setProducts] = useState([]);
const getProductsAPI = () => {
axios
.get("http://localhost:8000/api/products")
.then((res) => {
setProducts(res.data);
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
getProductsAPI();
}, [props]);
const InfoWrapper = styled.div`
text-align: center;
`;
return (
<div>
<InfoWrapper>
{products
.filter((product) =>
product.title.includes(props.searchTerm.toUpperCase())
)
.map((filteredItem, i) => (
<Item key={i}>
<ItemTitle> {filteredItem.title} </ItemTitle>
</Item>
))}
</InfoWrapper>
</div>
);
};
export default SearchInfo;
如果刷新页面,它将显示我的所有产品,而不仅仅是props.searchTerm
。
我怎样才能解决这个问题?好像我从路线传来的道具没开过
答案 0 :(得分:0)
searchTerm来自您传递的状态和道具,而不是来自URL。您需要从路由器获取参数并使用它,请参见https://reactrouter.com/web/api/Hooks/useparams
类似的东西:
<Router>
<SearchInfo path="/search/:searchterm"/>
</Router>
import { useParams } from "react-router-dom";
const SearchInfo = (props) => {
let { searchterm } = useParams();
// ...
return (
<div>
<InfoWrapper>
{products.filter((product) => product.title.includes(searchterm))
.map((filteredItem, i) => (
<Item key={i}>
<ItemTitle> {filteredItem.title} </ItemTitle>
</Item>
))}
</InfoWrapper>
</div>
);
};
答案 1 :(得分:0)
我不知道为什么您的SearchInfo
有path
作为道具,但是我认为path
应该由路由器管理,所以理想的结构应该是:
<Router path="/search/:searchterm" component={SearchInfo} />
然后,您可以轻松访问位置信息:
const SearchInfo = (props) => {
// Here is what you need
const {
match: { params },
} = props;
}