React / Redux Application Processing

I want to capture form values ​​when the user submits the form. The React manual shows the following:

var CommentForm = React.createClass({ handleAuthorChange: function(e) { this.setState({author: e.target.value}); }, handleTextChange: function(e) { this.setState({text: e.target.value}); }, handleSubmit: function(e) { e.preventDefault(); var author = this.state.author.trim(); var text = this.state.text.trim(); if (!text || !author) { return; } render: function() { return ( <form className="commentForm" onSubmit={this.handleSubmit}> 

This style pushes all state changes through the processing function to each input. If I were to continue working with Redux, I would add that I would add actions and action creators to the action, which seems like a lot of overhead.

Note that the handleSubmit argument is an event.

I came across the following kit to run React / Redux, which looks a lot easier to work with. It uses a combination of smart / container components and a silent / presentation component:

Container

 @connect( () => ({}), {initialize}) export default class Survey extends Component { ... handleSubmit = (data) => { window.alert('Data submitted! ' + JSON.stringify(data)); this.props.initialize('survey', {}); } render() return ( <SurveyForm onSubmit={this.handleSubmit}/> ) ... 

Presentation

 class SurveyForm extends Component { static propTypes = { handleSubmit: PropTypes.func.isRequired, } render() { const { handleSubmit } = this.props; return ( <div> <form className="form-horizontal" onSubmit={handleSubmit}> ... } } 

I don’t understand why the handler for the onSubmit form onSubmit accepts an event for its argument for the Facebook tutorial, but why the onSubmit accepts form data ... The starter kit uses the redux-form package, but I don’t see it directly affect the behavior this handler.

+3
reactjs redux react-redux redux-form
source share
1 answer

The key is in redux-form , which is used as the ES2016 decorator in the SurveyForm class.

 ... @reduxForm({ form: 'survey', fields: ['name', 'email', 'occupation', 'currentlyEmployed', 'sex'], validate: surveyValidation, asyncValidate, asyncBlurFields: ['email'] }) export default class SurveyForm extends Component { ... 

The decorator will act as a wrapping function for SurveyForm , returning the packaging component.

As you may have noticed, the SurveyForm component accepts the handleSubmit support, which is not passed in the container. This is because it is provided with the @reduxForm decorator. Then the event is processed, and the container handler is returned, only the Data form, the top level is onSubmit .

Essentially, you can think of it as reduxForm by returning a wrapped SurveyForm component.

You can dive into the code there , but be careful, it's pretty tight.

+4
source share

All Articles