D
D
Dmitry2019-04-18 23:19:36
React
Dmitry, 2019-04-18 23:19:36

How to pass props to state received using connect in React?

Hello. There is a form which has an initial state defined in constructor. Initially state filled in componentDidMount(). Now part of the data comes through connect (react-redux) and in componentDidMount it is empty. They are inside the render method. How to pass them to the state of the component? Below is the component code. It's all in the process of being redone.

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {validateEmail} from "../helpers/validation";

class ProductCommentsForm extends Component {

    constructor(props){
        super(props);
        
        this.state = {
            // START: input fields initional value
            userName: '',
            userEmail: '',
            productCommentContent: '',
            // END: input fields initional value
            productSlug: null,
            productID: null,
            userID: null,
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentDidMount(){
        const USER_ID = this.state.userID ? this.state.userID : 11

        console.log( 'this.props.myState', this.props.myState );

        /*this.setState({
            //comments: allComments,//is Array
            //users: users,// is Object
            userID: USER_ID,
            // if current user is logged out then userName is empty string
            // is for empty string validation before send request to server
            userName: (USER_ID === 11) ? '' : users[USER_ID]['name'],
            userEmail: users[USER_ID]['email'],
            userLogo: users[USER_ID]['logo'],
            commentsLength: allComments.length ? allComments.length : 0,
            productSlug: this.props.productSlug,
            productID: this.props.productID,
        });*/
    }

    handleChange(e){
        this.setState({
            [`${e.target.name}`]: e.target.value,
        });
    }

    handleSubmit(e){
        e.preventDefault();

        if ( this.state.productCommentContent && validateEmail(this.state.userEmail) && this.state.userName ) {
            const productComment = {
                content: this.state.productCommentContent,
                user_name: this.state.userName,
                user_email: this.state.userEmail,

                product_slug: this.state.productSlug,
                product_id: this.state.productID,
                user_id: this.state.userID,
            }

            axios.post('/api/product-comments', productComment).then(response => {
                const newCommentsList = [...this.state.comments, response.data];
                this.setState({
                    comments: newCommentsList,
                    commentsLength: newCommentsList.length,
                });
            });
        }
    }

    render(){

        // const {commentsLength, title, userName, userEmail, handleSubmit, handleChange} = this.props;
        const {userName, userEmail, handleSubmit, handleChange} = this.state;

        return (
            <div id="review_form_wrapper" className="review_form_wrapper">
                <div id="review_form">
                    <div id="respond" className="comment-respond">
                        {/*<span id="reply-title" className="comment-reply-title">
                            {commentsLength ? 'Ваша оценка' : `Будьте первым, кто оставил отзыв на “${title}”`} <small><a id="cancel-comment-reply-link" href="#" style={{display:'none'}}>Отменить ответ</a></small>
                        </span>*/}
                        <form
                            onSubmit={handleSubmit}
                            method="post"
                            id="commentform"
                            className="comment-form"
                            noValidate=""
                        >
                            <div className="reply-title-after">
                                Используйте данную форму, чтобы оставить отзыв о товаре или задать вопрос
                            </div>
                            <p className="comment-form-author">
                                <label>Ваше имя &nbsp;<span className="required">*</span></label>
                                <input
                                    onChange={handleChange}
                                    id="author"
                                    name="userName"
                                    type="text"
                                    size="30"
                                    aria-required="true"
                                    required=""
                                    defaultValue={userName}
                                />
                            </p>
                            <p className="comment-form-email">
                                <label>E-mail &nbsp;<span className="required">*</span></label>
                                <input
                                    onChange={handleChange}
                                    id="email"
                                    name="userEmail"
                                    type="email"
                                    size="30"
                                    aria-required="true"
                                    required=""
                                    defaultValue={userEmail}
                                />
                            </p>
                            <p className="comment-form-comment">
                                <label>Текст сообщения &nbsp;<span className="required">*</span></label>
                                <textarea
                                    onChange={handleChange}
                                    id="comment"
                                    name="productCommentContent"
                                    cols="45" rows="8"
                                >
                                </textarea>
                            </p>
                            <p className="form-submit">
                                <input name="submit" type="submit" id="submit" className="submit" value="Отправить"/>
                            </p>
                        </form>
                    </div>
                </div>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {myState: state.products.comments};
};

export default connect(mapStateToProps)(ProductCommentsForm);

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-04-18
@ddimonn8080

https://reactjs.org/docs/react-component.html#stat... will help you ,
but in fact you need to use props directly, store in state only what can change during the operation of the component itself with unchanged props

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question