Replies: 2 comments 3 replies
-
在router-v6中可以使用以下,目前使用良好 import React, { useCallback, useEffect, createContext, useContext } from "react";
import { useSearchParams, NavigateOptions } from "react-router-dom";
export const navigateOptions: NavigateOptions = {
replace: true,
};
export const UrlParamsContext = createContext<ReturnType<typeof useSearchParams>>([new URLSearchParams(), old => old]);
export const UrlParamsContextProvider: React.FC = ({ children }) => {
const urlParamsContext = useSearchParams();
return <UrlParamsContext.Provider value={urlParamsContext}>{children}</UrlParamsContext.Provider>;
};
export const useUrlState = (key: string, state: string) => {
const [searchParams, setSearchParams] = useContext(UrlParamsContext);
useEffect(() => {
const hasStateInUrl = searchParams.has(key);
const urlState = searchParams.get(key) || "";
if (!hasStateInUrl && urlState !== state) {
searchParams.set(key, state);
setSearchParams(searchParams, navigateOptions);
}
}, [searchParams, state, key]);
const setter = useCallback(
(newState: string) => {
searchParams.set(key, newState);
setSearchParams(searchParams, navigateOptions);
},
[key, searchParams]
);
return [searchParams.get(key) || state, setter, searchParams, setSearchParams] as const;
};
|
Beta Was this translation helpful? Give feedback.
1 reply
-
单参数的问题是,如果想更改多个属性,就会很麻烦,就像你 demo 里的三个属性,如果想同时更新呢 |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
期望useUrlState表现如下:
这样可以在多个子组件中创建或者修改唯一参数,或者某个组件修改这个参数后,其他组件获得响应。
它的体验类似于react-query的querykey。ahooks/useUrlState 则需要提前声明整个对象。
是否可以以单参数的形式,将大部分状态存储到url中,以便在跨组件时共享query的状态。
Beta Was this translation helpful? Give feedback.
All reactions