Skip to content

Commit 8ae3280

Browse files
committed
feat(Avatar): 优化Avatar组件图片加载逻辑,增强用户体验
1 parent 484d65c commit 8ae3280

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

app/components/ui/Avatar.tsx

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState } from 'react';
1+
import { useState } from 'react';
22

33
interface AvatarProps {
44
src: string;
@@ -7,13 +7,13 @@ interface AvatarProps {
77
}
88

99
export function Avatar({ src, alt, className = '' }: AvatarProps) {
10-
const [imgSrc, setImgSrc] = useState(src);
10+
const [imgSrc, setImgSrc] = useState(src.startsWith('http') ? src : `${window.ENV.OSS_HOST}${src}`);
1111
const [error, setError] = useState(false);
1212

1313
const handleError = () => {
1414
setError(true);
1515
// 设置一个默认的头像 URL
16-
setImgSrc('/avatars/default-avatar.png');
16+
setImgSrc(`${window.ENV.OSS_HOST}/avatars/default-avatar.png`);
1717
};
1818

1919
return (

app/root.tsx

+18-3
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
import { useStore } from '@nanostores/react';
2-
import type { LinksFunction } from '@remix-run/cloudflare';
3-
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from '@remix-run/react';
2+
import type { LinksFunction, LoaderFunction } from '@remix-run/cloudflare';
3+
import { json } from '@remix-run/cloudflare';
4+
import { Links, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData } from '@remix-run/react';
45
import tailwindReset from '@unocss/reset/tailwind-compat.css?url';
56
import { themeStore } from './lib/stores/theme';
67
import { stripIndents } from './utils/stripIndent';
78
import { createHead } from 'remix-island';
89
import { useEffect } from 'react';
10+
import { env } from 'node:process';
911

1012
import reactToastifyStyles from 'react-toastify/dist/ReactToastify.css?url';
1113
import globalStyles from './styles/index.scss?url';
@@ -62,9 +64,17 @@ export const Head = createHead(() => (
6264
</>
6365
));
6466

67+
export const loader: LoaderFunction = async () => {
68+
return json({
69+
ENV: {
70+
OSS_HOST: env.VITE_OSS_BASE_URL,
71+
},
72+
});
73+
};
74+
6575
export function Layout({ children }: { children: React.ReactNode }) {
6676
const theme = useStore(themeStore);
67-
77+
const data = useLoaderData<typeof loader>() as { ENV: { OSS_HOST: string } };
6878
useEffect(() => {
6979
document.querySelector('html')?.setAttribute('data-theme', theme);
7080
}, [theme]);
@@ -73,6 +83,11 @@ export function Layout({ children }: { children: React.ReactNode }) {
7383
<>
7484
{children}
7585
<ScrollRestoration />
86+
<script
87+
dangerouslySetInnerHTML={{
88+
__html: `window.ENV = ${JSON.stringify(data.ENV)}`,
89+
}}
90+
/>
7691
<Scripts />
7792
</>
7893
);

0 commit comments

Comments
 (0)