短信验证码获取表单

796 阅读1分钟

目标

能够使用redux发送请求获取验证码

步骤

  1. 在 Login 组件中导入获取验证码的 action
  2. 在获取验证码事件中分发获取验证码的 action
  3. 在 login action 中创建获取验证码的 action 并导出
  4. 发送请求获取验证码 如何获取form实例
const [form] = Form.useForm() 
<Form form={form} ></Form>

如何获取表单指定字段的数据

// 拿到手机号
const mobile = form.getFieldValue('mobile')

如何主动校验

// 判断手机号校验是否成功
const hasError = form.getFieldError('mobile').length > 0

落地代码: Snipaste_2021-12-02_21-29-21.png

11.png

222.png pages/Login/index.tsx 中:

const onSend = async () => {
    // 1. 验证表单元素-手机号格式
    if (form.getFieldError('mobile').length > 0) {
      // 让 手机号所在的文本框自动获取焦点
      refInput.current!.focus()
      return
    }
    // 2. 获取表单元素的值
    const mobile = form.getFieldValue('mobile')
    console.log('mobile', mobile)

    // 调用接口向mobile发验证码
    try {
      await dispatch(getCode(mobile))
      Toast.show({ content: '短信已发送' })
    } catch (e) {
      const error = e as AxiosError<{ message: string }>
      Toast.show({ content: error.response?.data.message })
    }
  }

actions/login.ts 中:

// 获取验证码 发送请求
export const getCode = (mobile: string) => {
  return async () => {
    await request.get(`/codes/${mobile}`)
​
    // 注意:验证码是发送到手机上的,因此,不需要更新Redux状态
  }
}