【发布时间】:2020-08-22 23:55:36
【问题描述】:
我正在使用 react-router-dom v5,并且 react 16
每当我这样导航时:
从“/products/:someId”到“/products/:someOtherId”
url 发生变化,但组件没有相应更新
查询也是如此。
“/products?search=something”或“/products?search=someOtherThing”
当我在不同的网址中时,它确实有效,例如“/”或“/users”,
我使用 Link 进行导航,我也尝试了 useHistory 钩子:history.push、history.replace 和 withRouter(myComponent);
这就是我从查询/参数中获取数据的方式
async function searchProducts(searchValue) {
const response = await axios.post(
"http://localhost:8000/api/products/search",
{ search: searchValue });
return response.data.body;
}
const useFetchData = (query) => {
const [products, setProducts] = useState([]);
useEffect(() => {
if (products.length === 0) {
// Use searchProducts for the request
searchProducts(query).then((foundProducts) => {
setProducts(foundProducts);
});
}
}, [products, query]);
return products;
};
然后我 useFetchData 在我的组件中:
const ProductList = () => {
const history = useHistory();
// parsing query to be -> { search: "value" }
const urlQuery = queryString.parse(history.location.search);
const products = useFetchData(urlQuery.search);
const getList = () => {
return products.map((product) => {
return (
<li key={product._id}>
<ProductItem product={product} />
</li>
);
});
};
return <div className="container">{getList()}</div>;
};
搜索按钮位于标题的不同组件中,它始终存在,因为它在布局中
<button className="header-search-button" onClick={handleClick}>
Search
</button>
和handleClick:
// searchvalue has it's own onChange handler
const [searchValue, setSearchValue] = useState("");
// code...
const handleClick = () => {
// .... some code
// I also tried with push and Link
history.replace(`/products?search=${searchValue}`);
};
【问题讨论】:
-
请根据参数发布您如何获取数据的代码
-
我贴了一些代码