[英]How do i sync my URL with application state using Nextjs
I have filters for my application.我的应用程序有过滤器。 I'd like to do shallow routing, and add the queries to the URL when a user changes the filters at the same time update my application state.
当用户更改过滤器同时更新我的应用程序 state 时,我想做浅层路由,并将查询添加到 URL。 But this seems like I'm maintaining two states.
但这似乎我在维持两种状态。 Are there any best practices for this?
有没有这方面的最佳实践? as i'd like my url to match application state
我希望我的 url 匹配应用程序 state
Derive your app state from the url.从 url 派生您的应用程序状态。 That means that you need to change the url, and the app will re-render -> derive the new state from the url.
这意味着您需要更改 url,应用程序将重新渲染 -> 从 url 派生新状态。
// somePage.jsx
import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';
const somePage = () => {
const router = useRouter();
const [myState, setMyState] = useState({ page: 1 });
useEffect(() => {
setState({ page: query.page });
}, [router.query.page]);
return (
<div>
{JSON.stringify(myState)}
{[1, 2, 3, 4, 5].map(page => (
<Link href={`?page=${page}`} key={page}>
<a>page {page}</a>
</Link>
))}
</div>
);
};
export default somePage;
You could extract this logic to a custom hook:您可以将此逻辑提取到自定义挂钩:
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
export const useQueryState = (initialState = {}) => {
const router = useRouter();
const [state, setState] = useState(initialState);
useEffect(() => {
setState(router.query);
}, [router.query]);
const setQueryParams = (query = {}) => {
router.push({ pathname: router.pathname, query }, undefined, {
shallow: true,
});
};
return [state, setQueryParams];
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.