首页 文章

Redux Form v6 - 正在调用onSubmit函数,但不调度动作

提问于
浏览
3

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

现在我只有一个按钮,应该发送一个动作 . 我看到了 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
  }
}

在其他组件中使用此方法调度操作时没有任何问题 . 我必须让redux配置错误,但我觉得我就像所描述的例子一样 .

如果我在道具中传递登录功能并将其传递给 handleSubmit ,就像这样

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

onSubmit 函数被调用,但它在 SET_SUBMIT_SUCCEEDED 之前被调用,这使我认为我添加的任何验证都不起作用,无论如何它都会提交 .

2 回答

  • 3

    您的 login 函数似乎应该有不同的签名 .

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

    将使用以下参数调用onSubmit:values:Object {field1:'value1',field2:'value2'}形式的字段值 . dispatch:Function Redux调度功能 . props:Object传递到装饰组件的props .

    尝试以下方法:

    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 })))
      }
    }
    
  • 3

    这很有效

    const login = (values, 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 })))
    }
    

相关问题