首页 > 解决方案 > 使用 React Final Form 的 Redux 调度

问题描述

我试图了解为什么dispatch在我的操作中无法使用无济于事。这是我尝试过的。

import React, { Component } from 'react';

import { connect } from 'react-redux';
import { Field, Form } from 'react-final-form';

import { createProfile } from '../../actions/actions_members';

const onSubmit = async (values) => {
    createProfile(values)
}

const Signup = () => (
  <Form
    onSubmit={onSubmit}
    render={({ handleSubmit, submitting, pristine, values }) => (
        <form onSubmit={handleSubmit} >
            <label>Email:</label>
            <Field type='text' className='input' component="input" type="text" name='email'/>
            <label>Password:</label>
            <Field className='input' component="input" type="password" name='password' />
            {/*<label>Confirm password:</label>
            <input type='password' className='input' name='password' {...password} />*/}
            <button type="submit" disabled={submitting || pristine}>
              Submit
            </button>
        </form>
    )}
  />
)

export default connect()(Signup)

这是我的actions_members文件

import * as C from './actions_const.js'

import { post, get } from '../helpers/apiConnection.js'

const createProfile = (value, dispatch) => {
    var data = {
      ep: "EP_SIGNUP",
      payload : {
        email: value.email,
        password: value.password
      }
    }
    post(data).then((result)=>dispatch({type:C.MEMBER_CREATE}));
}
export { createProfile }

我不知道如何传递dispatch给我的createProfile行动

标签: reactjsreduxreact-final-form

解决方案


你只需要从onSubmit函数中传递它。

const dispatch = useDispatch();

const onSubmit = async (values) => {
    createProfile(values, dispatch)
}

另一种选择是将商店导入您的 action_members 文件并使用 store.dispatch,这相当于同一件事。

import * as C from './actions_const.js'

import { post, get } from '../helpers/apiConnection.js'

import store from '../whereverReduxStoreIsSetup.js';

const createProfile = (value) => {
    var data = {
      ep: "EP_SIGNUP",
      payload : {
        email: value.email,
        password: value.password
      }
    }
    post(data).then((result)=>store.dispatch({type:C.MEMBER_CREATE}));
}
export { createProfile }

推荐阅读