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