第77天:修复 React Hydration 与 AWS SES 身份

发布: (2026年5月9日 GMT+8 00:00)
3 分钟阅读
原文: Dev.to

Source: Dev.to

Day 77:修复 React 水合问题与 AWS SES 身份验证的封面图片

React 头像闪烁

我遇到了经典的数据水合问题。当用户登录时,React 同步渲染一个默认头像,等待约 200 毫秒让 DynamoDB 返回真实的头像 URL,然后立刻把新图片替换进去。

解决方案: 在加载状态下停止渲染占位符。当 !isAvatarLoading 时,组件仅保留一个干净的白色圆圈。结合 localStorage 缓存,返回的用户可以瞬间加载,新的用户则能获得没有突兀布局移动的流畅体验。

// Example React avatar component
import React, { useEffect, useState } from 'react';

function Avatar({ userId }) {
  const [avatarUrl, setAvatarUrl] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const cached = localStorage.getItem(`avatar-${userId}`);
    if (cached) {
      setAvatarUrl(cached);
      setIsLoading(false);
      return;
    }

    fetch(`/api/users/${userId}/profile`)
      .then(res => res.json())
      .then(data => {
        setAvatarUrl(data.avatarUrl);
        localStorage.setItem(`avatar-${userId}`, data.avatarUrl);
      })
      .finally(() => setIsLoading(false));
  }, [userId]);

  return (
    {isLoading ? (
      // placeholder (e.g., empty circle)
    ) : (
      // render <img src={avatarUrl} alt="User avatar" />
    )}
  );
}

AWS SES 中的机器人邮件

我的 Python Lambda 使用以下方式通过 SES 发送每日报告:

Source = "ai@duromoney.com"

虽然技术上是正确的,但邮件在收件箱中显得不够可信。

解决方案:Source 字段中加入友好的发件人名称:

Source = "DuroAI <ai@duromoney.com>"

Gmail 和 Outlook 现在会显示 “DuroAI” 作为发件人名称。我还借此机会实现了一个事件驱动的欢迎邮件。当用户的个人资料首次保存在 DynamoDB 时,Lambda 路由器拦截负载并触发自定义的 SES 欢迎模板。

import boto3

ses = boto3.client('ses')

def send_welcome_email(user_email, user_name):
    response = ses.send_email(
        Source="DuroAI <ai@duromoney.com>",
        Destination={'ToAddresses': [user_email]},
        Message={
            'Subject': {'Data': f'Welcome, {user_name}!'},
            'Body': {
                'Html': {'Data': f'''
## Hello {user_name}

Welcome to DuroAI.
''' }
            }
        },
        ReplyToAddresses=['support@duromoney.com']
    )
    return response

结果是邮件看起来更可信,用户的入职体验也更加顺畅。

0 浏览
Back to Blog

相关文章

阅读更多 »