How to get history and match in this.props in nextjs?

那年仲夏 提交于 2021-01-28 18:44:05

问题


I want to get values of history and match in this.props.Iam using next/router to import withouter.I wanted to use this.props.match.params to get values in the url and history.push to redirect.How can get this in next.js . Rightnoe iam not getting history and match in this.props.


回答1:


next/router doesn't provide you history as react-dom-router does, it gives you something called query in your component's props.

This is the official usage example.

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { pid } = router.query

  return <p>Post: {pid}</p>
}

export default Post

If you want to push routes, you can follow this one. example.

import Router from 'next/router'

function ReadMore() {
  return (
    <div>
      Click <span onClick={() => Router.push('/about')}>here</span> to read more
    </div>
  )
}

export default ReadMore



回答2:


You can as well use Router

import Router from 'next/router'
// on Submit handler
Router.push(url)

where url is the page you want to redirect to.

Router API




回答3:


I have not found an elegant way to be able to access Router.history in its entirety. But often enough I wanted to access at least the last visited route, which forced me to this workaround. It might not be the most elegant way since it pollutes the global Router object, but as I said I have not found any alternative.

I only check for the actual route which was visited previously. You may also implement your logic to check the params. The hook plugs-in before the Router handles the actual Route change. Which allows you to listen to the Router.previousRoute property within you application.

KEEP IN MIND if you do shallow Routing you may not affect the Router.history, which will probably not trigger this event hook.

const EXCEPTIONS = ['/sign-up'];

/**
 * Saves the current URL before changing the route.
 * The previousRoute is then accessible via the global Router.
 */
const useRouteUrlHistory = () => {
  const handleBeforeHistoryChange = (url) => {
    const [nextUrl] = url?.split('?') || [];

    if (
      !(EXCEPTIONS.includes(nextUrl) || EXCEPTIONS.includes(Router.asPath)) &&
      nextUrl !== Router.asPath
    ) {
      Router.previousRoute = Router.asPath;
    }
  };

  useEffect(() => {
    Router.events.on('beforeHistoryChange', handleBeforeHistoryChange);

    return () => {
      Router.events.off('beforeHistoryChange', handleBeforeHistoryChange);
    };
  }, []);
};

export default useRouteUrlHistory;


来源:https://stackoverflow.com/questions/56857880/how-to-get-history-and-match-in-this-props-in-nextjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!