简体   繁体   中英

NextJS navigation to same page and different query wont trigger hooks

Using NextJS, no SSR. Trying to do basic navigation, with different query params. After first arrival on the page/component. Component gets mounted, and hooks are no longer being triggered (hooks wont fire any of my async calls to the backend), HOWEVER I see the url params changing.

<Link
  key={booking.booking_ID}
  href={{ pathname: '/booking', query: { id: booking.booking_ID } }}
  replace>
  <SomeFancyButtonHere /
</Link>

Also tried Router push approach (same results)

onClick={() => Router.push({ pathname: '/booking', query: { id: booking.booking_ID } })}

Booking page hook:

  // component
  const query = queryString.parse(window.location.search);
  const { id } = query;
  useEffect(() => {
    fetchBookingById(id);
  }, []);

  return <SomeJsxStuffForBookingPage />

Only solution so far:

onClick={() => {
  Router.push({ pathname: '/booking', query: { id: booking.booking_ID } });
  setTimeout(() => {
    location.reload();
  }, 600);
}}

Essentially what I ended up doing:

const CartItem = ({ setActiveBookingId }) => (
<FancyButton
  onClick={async () => {
    await Router.push({ pathname: '/booking', query: { id: booking.booking_ID } });
    setActiveBookingId(booking.booking_ID);
  }}
/>)

const mapStateToProps = () => ({});
const mapDispatchToProps = {
  setActiveBookingId,
};
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(CartItem);

Redux action

export const setActiveBookingId = id => ({
  type: types.SET_ACTIVE_BOOKING_ID,
  id,
});

Reducer

case types.SET_ACTIVE_BOOKING_ID: {
  return {
    ...state,
    activeBooking: action.id,
  };
}

Final for fetching data

  useEffect(() => {
    if (id === activeBooking) {
      fetchBookingById(id);
      resetBookingCancelAndUpdate();
    }
  }, [activeBooking]);

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