How to handle redux-form/CHANGE in reducer

走远了吗. 提交于 2020-01-01 07:08:11

问题


What is the recommended way to handle redux-form/CHANGE actions being dispatched by redux-form? I have my own reducer managing the state of this form but I'm not sure if it's best to do the following:

export default reducer (state = initialState, action) {
  case 'redux-form/CHANGE':
    // return modified state
}

One problem I see is that this reducer would receive every redux-form/CHANGE action. Additionally as far as I can tell ActionTypes.js isn't exported in a way for me to import it so I feel as though this may not be best practice.


回答1:


You can definitely use redux-form action creators. You just have to connect it to your component.

So in your /components/MyComponent.js

import React from 'react';
import { connect } from 'react-redux';
import { change } from 'redux-form';

class MyComponent extends React.Component {
    ...
    render() {
        return <div>
            <button onClick={this.props.change('formName', 'fieldName', 'value')}>Change</button>
        </div>
    }
}

const mapStateToProps = (state, ownProps) => { ... }
export default connect(mapStateToProps, { change })(MyComponent);

You could also use redux-form reducer and extends it to your needs...

In your reducers/index.js]

import { reducer as form } from 'redux-form';

const formPlugin = {
    formName: (state, action) => {
        ...reducer logic
        return newState;
    }
}

const rootReducer = combineReducers({
    ...other reducers,
    form: form.plugin(formPlugin)
});


来源:https://stackoverflow.com/questions/40693973/how-to-handle-redux-form-change-in-reducer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!