我正在尝试使用 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/