简体   繁体   中英

Next.js router: how to make page refresh on url change?

I have page where a user can narrow their search using filters. The issue is that when a user clicks on a filter to filter properties by "rent" or "buy", the url does not refresh to reflect the changes. The changes do however appear in the URL, which is what I want, but I have to manually press enter to refresh the page with the specified filters, so that changes would appear.

在此处输入图像描述

As you can see in the photo, the properties listed are not "for rent" properties, so the only way to correctly see the rental properties is to manually enter the url: http://localhost:3000/search?purpose=for-rent&minPrice=20000

import {
  Flex,
  Select,
  Box,
} from "@chakra-ui/react";
import { useRouter } from "next/router";
import Image from "next/image";
import { filterData, getFilterValues } from "../utils/filterData";

class searchFilters extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filters: filterData,
    };
  }

  handleChange = (filterValues) => {
    const path = this.props.params.pathname;
    const { query } = this.props.params;
    const values = getFilterValues(filterValues);
    values.forEach((item) => {
      if (item.value && filterValues?.[item.name]) {
        query[item.name] = item.value;
      }
    });
    this.props.params.push({ pathname: path, query: query });
  };

  render() {
    const { filters } = this.state;
    return (
      <Flex bg="gray.100" p="4" justifyContent="center" flexWrap="wrap">
        {filters.map((filter) => (
          <Box key={filter.queryName}>
            <Select
              placeholder={filter.placeholder}
              w="fit-content"
              p="2"
              onChange={(e) =>
                this.handleChange({ [filter.queryName]: e.target.value })
              }
            >
              {filter.items.map((item) => (
                <option value={item.value} key={item.value}>
                  {item.name}
                </option>
              ))}
            </Select>
          </Box>
        ))}
      </Flex>
    );
  }
}

const withParams = (Component) => {
  return (props) => <Component {...props} params={useRouter()} />;
};

export default withParams(searchFilters);

As you are using the same component, it will not reload the page. You can detect the param change with useEffect hook and add the refreshig logic within it. This would reload the data as per the new param.

const { query } = useRouter();

useEffect(() => {
  // Refresh logic
}, [query.purpose)]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM