zustand-querystring 中文文档教程
zustand-querystring
将状态与查询字符串同步的 zustand 中间件。
尝试 StackBlitz (您需要单击“在新选项卡中打开”)
示例:
快速入门:
import create from "zustand";
import { querystring } from "zustand-querystring";
interface Store {
count: number;
ticks: number;
someNestedState: {
nestedCount: number;
hello: string;
};
}
export const useStore = create<Store>()(
querystring(
(set, get) => ({
count: 0,
ticks: 0,
someNestedState: {
nestedCount: 0,
hello: "Hello",
},
}),
{
// select controls what part of the state is synced with the query string
// pathname is the current route (e.g. /about or /)
select(pathname) {
return {
count: true,
// ticks: false, <- false by default
someNestedState: {
nestedCount: true,
hello: "/about" === pathname,
},
// OR select the whole nested state
// someNestedState: true
};
},
}
)
);
查询字符串选项:
- select - select 选项控制状态的哪一部分与查询字符串同步
- key: string - key 选项控制如何同步状态存储在查询字符串中(默认:$)
- url - url 选项用于在服务器端渲染上提供请求 url
zustand-querystring
A zustand middleware that syncs state with the querystring.
Try on StackBlitz (You need to click "Open in New Tab")
Examples:
Quickstart:
import create from "zustand";
import { querystring } from "zustand-querystring";
interface Store {
count: number;
ticks: number;
someNestedState: {
nestedCount: number;
hello: string;
};
}
export const useStore = create<Store>()(
querystring(
(set, get) => ({
count: 0,
ticks: 0,
someNestedState: {
nestedCount: 0,
hello: "Hello",
},
}),
{
// select controls what part of the state is synced with the query string
// pathname is the current route (e.g. /about or /)
select(pathname) {
return {
count: true,
// ticks: false, <- false by default
someNestedState: {
nestedCount: true,
hello: "/about" === pathname,
},
// OR select the whole nested state
// someNestedState: true
};
},
}
)
);
querystring options:
- select - the select option controls what part of the state is synced with the query string
- key: string - the key option controls how the state is stored in the querystring (default: $)
- url - the url option is used to provide the request url on the server side render