fix(brand): brand更新不及时的问题
This commit is contained in:
parent
c45bc4d521
commit
03ff3ece7f
@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import { useLayoutEffect } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
import { useBrand } from "./provider";
|
import { useBrand } from "./provider";
|
||||||
|
|
||||||
@ -10,25 +10,32 @@ import {
|
|||||||
readStoredBrand,
|
readStoredBrand,
|
||||||
resolveBrandSession,
|
resolveBrandSession,
|
||||||
writeStoredBrand,
|
writeStoredBrand,
|
||||||
|
type Brand,
|
||||||
} from "./index";
|
} from "./index";
|
||||||
|
|
||||||
export function BrandSessionInitializer() {
|
export function BrandSessionInitializer() {
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const { setBrand } = useBrand();
|
const { brand, setBrand } = useBrand();
|
||||||
|
const prevBrandRef = useRef<Brand>(brand);
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
// 在 render 阶段同步计算,确保每次 searchParams 变化都能感知
|
||||||
const storedBrand = readStoredBrand(window.sessionStorage);
|
const storedBrand =
|
||||||
const urlBrand = parseBrandFromSearchParams(
|
typeof window !== "undefined"
|
||||||
new URLSearchParams(searchParams.toString()),
|
? readStoredBrand(window.sessionStorage)
|
||||||
);
|
: null;
|
||||||
const resolvedBrand = resolveBrandSession({
|
const urlBrand = parseBrandFromSearchParams(
|
||||||
urlBrand,
|
new URLSearchParams(searchParams.toString()),
|
||||||
storedBrand,
|
);
|
||||||
});
|
const resolvedBrand = resolveBrandSession({ urlBrand, storedBrand });
|
||||||
|
|
||||||
writeStoredBrand(window.sessionStorage, resolvedBrand);
|
// 只在品牌确实变化时才写入 sessionStorage 并更新 context
|
||||||
setBrand(resolvedBrand);
|
useEffect(() => {
|
||||||
}, [searchParams, setBrand]);
|
if (resolvedBrand !== prevBrandRef.current) {
|
||||||
|
prevBrandRef.current = resolvedBrand;
|
||||||
|
writeStoredBrand(window.sessionStorage, resolvedBrand);
|
||||||
|
setBrand(resolvedBrand);
|
||||||
|
}
|
||||||
|
}, [resolvedBrand, setBrand]);
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user