You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用对接AWS Amplify DataStore:数据连接、获取与校验咨询

解决AWS Amplify DataStore结合React开发的三个问题

1. React前端配置DataStore连接

  • 安装依赖:
    npm install aws-amplify @aws-amplify/ui-react
    
  • 在项目入口文件(src/index.js或src/main.jsx)中配置Amplify:
    import { Amplify } from 'aws-amplify';
    import awsExports from './aws-exports';
    
    Amplify.configure(awsExports);
    
    注:aws-exports.js是执行amplify push后自动生成的配置文件,包含你的AWS资源密钥和端点信息。
  • 验证连接:在任意组件中测试查询数据:
    import { useEffect } from 'react';
    import { DataStore } from '@aws-amplify/datastore';
    import { User } from './models';
    
    function App() {
      useEffect(() => {
        const fetchUsers = async () => {
          const users = await DataStore.query(User);
          console.log('已存储的用户数据:', users);
        };
        fetchUsers();
      }, []);
    
      return <div>测试DataStore连接</div>;
    }
    
    export default App;
    

2. 前端输入字段获取与校验

用React状态管理表单数据,搭配原生校验逻辑实现:

import { useState } from 'react';

function RegisterForm() {
  const [formData, setFormData] = useState({
    firstname: '',
    lastname: '',
    mobileno: '',
    city: '',
    state: ''
  });
  const [errors, setErrors] = useState({});

  // 同步输入值到状态
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    // 清除当前字段的错误提示
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  // 表单校验逻辑
  const validateForm = () => {
    const newErrors = {};
    // 必填校验
    if (!formData.firstname.trim()) newErrors.firstname = '名字不能为空';
    if (!formData.lastname.trim()) newErrors.lastname = '姓氏不能为空';
    if (!formData.city.trim()) newErrors.city = '城市不能为空';
    if (!formData.state.trim()) newErrors.state = '州/省份不能为空';
    // 手机号格式校验(示例:10-15位数字)
    const phoneRegex = /^[0-9]{10,15}$/;
    if (!phoneRegex.test(formData.mobileno)) newErrors.mobileno = '请输入有效的手机号';

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (validateForm()) {
      // 校验通过,执行存储逻辑
      console.log('表单数据有效:', formData);
    }
  };

  return (
    <form onSubmit={handleSubmit} style={{ maxWidth: '400px', margin: '2rem auto' }}>
      <div style={{ marginBottom: '1rem' }}>
        <label>名字:</label>
        <input
          type="text"
          name="firstname"
          value={formData.firstname}
          onChange={handleChange}
          style={{ marginLeft: '0.5rem', padding: '0.3rem' }}
        />
        {errors.firstname && <p style={{ color: 'red', margin: '0.2rem 0 0 0' }}>{errors.firstname}</p>}
      </div>
      <div style={{ marginBottom: '1rem' }}>
        <label>姓氏:</label>
        <input
          type="text"
          name="lastname"
          value={formData.lastname}
          onChange={handleChange}
          style={{ marginLeft: '0.5rem', padding: '0.3rem' }}
        />
        {errors.lastname && <p style={{ color: 'red', margin: '0.2rem 0 0 0' }}>{errors.lastname}</p>}
      </div>
      <div style={{ marginBottom: '1rem' }}>
        <label>手机号:</label>
        <input
          type="tel"
          name="mobileno"
          value={formData.mobileno}
          onChange={handleChange}
          style={{ marginLeft: '0.5rem', padding: '0.3rem' }}
        />
        {errors.mobileno && <p style={{ color: 'red', margin: '0.2rem 0 0 0' }}>{errors.mobileno}</p>}
      </div>
      <div style={{ marginBottom: '1rem' }}>
        <label>城市:</label>
        <input
          type="text"
          name="city"
          value={formData.city}
          onChange={handleChange}
          style={{ marginLeft: '0.5rem', padding: '0.3rem' }}
        />
        {errors.city && <p style={{ color: 'red', margin: '0.2rem 0 0 0' }}>{errors.city}</p>}
      </div>
      <div style={{ marginBottom: '1rem' }}>
        <label>州/省份:</label>
        <input
          type="text"
          name="state"
          value={formData.state}
          onChange={handleChange}
          style={{ marginLeft: '0.5rem', padding: '0.3rem' }}
        />
        {errors.state && <p style={{ color: 'red', margin: '0.2rem 0 0 0' }}>{errors.state}</p>}
      </div>
      <button type="submit" style={{ padding: '0.5rem 1rem' }}>提交注册</button>
    </form>
  );
}

export default RegisterForm;

3. 将注册数据存储到DataStore

步骤1:确保数据模型包含所需字段

在amplify/backend/api/[你的API名称]/schema.graphql中定义User模型:

type User @model {
  id: ID!
  firstname: String!
  lastname: String!
  mobileno: String!
  city: String!
  state: String!
}

执行以下命令更新云端资源:

amplify push

步骤2:在表单中添加存储逻辑

修改RegisterForm组件的handleSubmit函数,引入DataStore保存数据:

import { DataStore } from '@aws-amplify/datastore';
import { User } from './models'; // 自动生成的模型文件

// ... 其他代码 ...

const handleSubmit = async (e) => {
  e.preventDefault();
  if (validateForm()) {
    try {
      const newUser = await DataStore.save(
        new User({
          firstname: formData.firstname,
          lastname: formData.lastname,
          mobileno: formData.mobileno,
          city: formData.city,
          state: formData.state
        })
      );
      alert('注册成功!');
      console.log('新用户数据:', newUser);
      // 重置表单
      setFormData({
        firstname: '',
        lastname: '',
        mobileno: '',
        city: '',
        state: ''
      });
    } catch (err) {
      console.error('存储失败:', err);
      alert('注册失败,请稍后重试');
    }
  }
};

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:05:10