【问题标题】:Router calling with template URI parameters使用模板 URI 参数调用路由器
【发布时间】:2021-04-01 23:28:57
【问题描述】:

我正在使用useRouter 钩子。

我的应用程序中有模板页面。

我有一个 useEffect 挂钩响应 router 并进行 API 调用。

我正在尝试将整个 URL 转发到 /api/${path}.json${query}

const u = new URL(`https://example.com${router.asPath}`)
const path = `/api${u.pathname}.json${u.search}`

但是路由器似乎触发了两次,一次作为模板,另一次作为填充参数,例如:

  1. /[design]/[product]
  2. /blue/shirt

这必然会触发对 API 的两次调用。

这是我的钩子:

export const usePage = () => {
    const router = useRouter();
    const [page, setPage] = useState()
    useEffect(() => {
        (async () => {
            // the next.js query is littered with the params, so we can get
            // just the query with this:
            const u = new URL(`https://example.com${router.asPath}`)
            const path = `/api${u.pathname}.json${u.search}`
            console.log({ path })
            const results = await fetch(path, { method: 'GET' });
            const json = await results.json();
            setPage(json)
        })();
    }, [router]);
    return page;
}

我可以将调用包装在条件检查中以查看 url 中是否有 [|],并且不要运行 api 调用。想知道有没有更好的方法。

【问题讨论】:

  • 什么将router.asPath 设置为/[design]/[product]?除非您将外部路由更改为 usePage,否则 useEffect 应该只触发一次。

标签: typescript next.js


【解决方案1】:

创可贴解决方案:?

export const usePage = () => {
    const router = useRouter();
    const [page, setPage] = useState()
    useEffect(() => {
        (async () => {
            // the next.js query is littered with the params, so we can get
            // just the query with this:
            const u = new URL(`https://example.com${router.asPath}`)
            if (u.pathname.match(/\[/)) return;
            const path = `/api${u.pathname}.json${u.search}`
            const results = await fetch(path, { method: 'GET' });
            const json = await results.json();
            setPage(json)
        })();
    }, [router]);
    return page;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 2013-11-24
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    相关资源
    最近更新 更多