【发布时间】:2019-07-21 08:49:42
【问题描述】:
我正在尝试为表格编写搜索过滤器功能。我正在使用 react-router-dom v4。 当用户单击搜索按钮时,我想通过 props.history.push() 将页面从“/list”导航到“list?search=abc”。 (我已经使用了 RouteComponentProps 和 withRouter)。 但是我知道 react-router-dom v4 只是更改了 url 而不会刷新页面。 我的同事在类组件中使用函数 componentWillReceiveProps 来检测查询参数的变化。 (现在该函数称为 getDerivedStateFromProps)
componentWillReceiveProps(nextProps) {
console.log("next Props");
if (nextProps.location.search !== this.props.location.search) {
let parsed = queryString.parse(nextProps.location.
this.loadData(parsed);
}
在功能组件中使用 React Hook(带有 Typescript)对我来说是强制性的。我尝试了很多方法,但没有奏效。 你知道解决这个问题的方法吗? 非常感谢。
【问题讨论】:
-
我找到了我的解决方案,我使用 useEffect 来检测更改搜索 useEffect(() => { console.log(
use effect set state search); const searchParams = new URLSearchParams(props.location.search); console .log(search params: ${searchParams}); const search = searchParams.get("search") || ""; console.log(search: ${search}); setState({ ...state, search: search }); loadData(search ); }, [新 URLSearchParams(props.location.search).get("search")]); -
请将您的解决方案添加为答案而不是评论。然后您可以接受自己的答案,其他人会更清楚这个问题已经得到回答。
-
我已经搞定了,谢谢提醒
标签: reactjs typescript react-router-v4 react-hooks