Здравствуйте. Есть форма у которой есть начальное состояние определяемое в constructor. Изначально state заполнял в componentDidMount(). Сейчас часть данных приходят через connect(react-redux) и в componentDidMount они пустые. Они есть внутри render метода. Как их передать в state компонента? Ниже код компонента. Там все в процессе переделки.
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>Ваше имя <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 <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>Текст сообщения <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);
Спасибо.