【问题标题】:React router v4 history.push to the same route (different query params) in Functional Component (use Hooks API)将路由器 v4 history.push 反应到功能组件中的同一路由(不同的查询参数)(使用 Hooks API)
【发布时间】: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


【解决方案1】:

我找到了我的解决方案,我使用 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); 
}, [props.location.search]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2020-10-17
    • 1970-01-01
    • 2021-03-17
    • 2017-12-06
    • 2021-11-19
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多