javascript - Redux Form v6 - 调用 onSubmit 函数,但不调度操作

标签 javascript forms reactjs redux redux-form

我正在尝试使用 redux-form 设置一个简单的表单。

现在我只有一个按钮,它应该发送一个 Action 。我看到 SET_SUBMIT_SUCCEEDED 操作,所以我知道表单已成功提交,并且我可以看到正在调用我指定的 onSubmit 函数,但它没有调度操作。

// root reducer
import { combineReducers } from 'redux'
import { reducer as reduxFormReducer } from 'redux-form'
import login from './login'

export default combineReducers({
  login,
  form: reduxFormReducer
})


// action-creator
import { createAction } from './create_action'
import { postJson } from './fetch'
import {
  LOGIN_ERROR,
  LOGIN_REQUEST,
  LOGIN_SUCCESS
} from '../constants/constants'

const login = () => {
  return function (dispatch) {
    dispatch(createAction(LOGIN_REQUEST))
    return postJson('/login')
      .then(res => res.json())
      .then(data =>
        dispatch(createAction(LOGIN_SUCCESS, { data }))
      )
      .catch(error => dispatch(createAction(LOGIN_ERROR, { error })))
  }
}


//component
import React from 'react'
import { reduxForm } from 'redux-form'
import login from '../redux/submit-handlers/login'

const Login = (props) => {
  const { handleSubmit } = props
  return (
    <form onSubmit={handleSubmit}>
      <h3>Login</h3>
      <button>Login</button>
    </form>
  )
}

export default reduxForm({
  form: 'login',
  onSubmit: login
})(Login)



//create_action
export const createAction = (type, payload) => {
  return {
    type,
    payload
  }
}

我在其他组件中使用这种方法分派(dispatch)操作时没有遇到任何问题。我一定是在 redux 上配置了一些错误,但我觉得我正在按照所描述的示例进行操作。

如果我在 props 中向下传递登录函数并将其传递给 handleSubmit,就像这样

<form onSubmit={handleSubmit(() => {login()})}>

调用了 onSubmit 函数,但它是在 SET_SUBMIT_SUCCEEDED 之前调用的,这让我觉得我添加的任何验证都不起作用,但无论如何它都会提交。

最佳答案

看来您的login 函数应该有不同的签名。

通过查看文档 http://redux-form.com/6.2.0/docs/api/ReduxForm.md/

onSubmit will be called with the following parameters:

values : Object The field values in the form of { field1: 'value1', field2: 'value2' }.

dispatch : Function The Redux dispatch function.

props : Object The props passed into your decorated component.

试试这样的:

const login = ({dispatch}) => {
  dispatch(createAction(LOGIN_REQUEST))
  return postJson('/login')
    .then(res => res.json())
    .then(data =>
      dispatch(createAction(LOGIN_SUCCESS, { data }))
    )
    .catch(error => dispatch(createAction(LOGIN_ERROR, { error })))
  }
}

关于javascript - Redux Form v6 - 调用 onSubmit 函数,但不调度操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40824932/

相关文章:

php - 使用 Google API 根据城市和州生成邮政编码

javascript - 使用 jQuery 将输入框标题设置为值

forms - 如何使用 pwsh 中的新 param -form 登录网站

reactjs - 如何修复 React/Redux/Firebase 将文件上传到存储时出错

javascript - 插件未按预期工作,可能存在 Javascript/jQuery 变量范围问题

javascript - 在 Angular JS ui 路由器中使用 ui-sref 时,不会生成 href

javascript - 使用 jQuery/JavaScript 获取表单对选择框更改的操作

reactjs - 我想在“下一步”中重定向用户而不使用 <Link>。 React Router 有 useNavigate(),那么 Next Router 有类似的东西吗?

css - SVG 的绝对定位导致内部路径元素移动到其包含元素之外

javascript - 在 Titanium SDK 中保存和检索 HTML 和 .aspx 网页