首页 > reactjs > 将路由器v4 history.push反馈到功能组件中的相同路由(不同的查询参数)(使用Hooks API)

将路由器v4 history.push反馈到功能组件中的相同路由(不同的查询参数)(使用Hooks API) (React router v4 history.push to the same route (different query params) in Functional Component (use)

问题

我正在尝试为表格编码搜索过滤器功能。我正在使用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); 
}, [props.location.search]);


问题

I am trying to code search filter feature for table. I am using react-router-dom v4. When user click search button, I want to navigate page from "/list" to "list?search=abc" by props.history.push(). (I already used RouteComponentProps and withRouter). But I know react-router-dom v4 just changes url while it doesn't not refresh the page. My colleague uses function componentWillReceiveProps in class component to detect query params changes. (now that function is known as getDerivedStateFromProps)

componentWillReceiveProps(nextProps) {
   console.log("next Props");
   if (nextProps.location.search !== this.props.location.search) {
     let parsed = queryString.parse(nextProps.location.
     this.loadData(parsed);
   }

Using React Hook (with Typescript) in functional component is compulsory to me. I tried many ways but it didn't work. Do you know the way to figure this issue out? Thank you very much.

解决方法

I found my solution, I use useEffect to detect query params search change

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]);

相似信息