Вызываемое действие React-Redux в prop не дает необходимых результатов - PullRequest
0 голосов
/ 04 января 2019

Я реализую компонент, который обрабатывает избыточное действие для добавления комментариев, но он не работает. Нет сгенерированной ошибки

Я пытался вызывать реквизиты из других регионов в коде, но, похоже, это не сработало. Действие addComment должно добавлять комментарии, представленные в разделе комментариев DishDetails. Однако никаких добавлений не производится.

ActionTypes.js

export const ADD_COMMENT='ADD_COMMENT';

ActionCreators.js

import * as ActionTypes from './ActionTypes';


export const addComment=(dishId,rating, author, comment)=>({
    type: ActionTypes.ADD_COMMENT,
    payload: {
        dishId:dishId,
        rating:rating,
        author:author,
        comment:comment
    }
});

comments.js

import { COMMENTS } from '../shared/comments';
import * as ActionTypes  from './ActionTypes';

export const Comments= (state= COMMENTS, action) => {
    switch(action.type){

        case ActionTypes.ADD_COMMENT:
            var comment= action.payload;
            comment.id= state.length;
            comment.date = new Date().toISOString();
            return state.concat(comment);

        default:
            return state;
    }
};

MainComponent.js

import React, { Component } from 'react';
import Header from './HeaderComponent';
import Footer from './FooterComponent';
import Menu from './MenuComponent';
import DishDetail from './DishDetail';
import Home from './HomeComponent';
import { Switch, Route, Redirect, withRouter } from 'react-router-dom'; 
import Contact from './ContactComponent';
import About from './AboutComponent';
import { connect } from 'react-redux';
import {addComment} from '../redux/ActionCreators';

const mapStateToProps = state =>{
  return{
    dishes: state.dishes,
    comments: state.comments,
    promotions: state.promotions,
    leaders: state.leaders
  }
};

const mapDispatchToProps = dispatch => ({
  addComment: (dishId,rating, author, comment)=>dispatch(addComment(dishId,rating, author, comment))
});

class Main extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    const HomePage= ()=>{
      return(
        <Home dish={this.props.dishes.filter((dish)=>dish.featured)[0]}
              promotion={this.props.promotions.filter((promotion)=>promotion.featured)[0]}
              leader={this.props.leaders.filter((leader)=>leader.featured)[0]}
              />
      );
    }

    const DishWithId = ({match})=>{
      return(
        <DishDetail dish={this.props.dishes.filter((dish)=>dish.id === parseInt(match.params.dishId,10))[0]}
                    comments={this.props.comments.filter((comment)=>comment.dishId=== parseInt(match.params.dishId,10))}
                    addComment={this.props.addComment}/>
      );
    }

    const AboutPage = ()=>{
      return(
        <About leaders={this.props.leaders}/>
      );
    }
    return (
      <div>
       <Header/> 
       <Switch>
          <Route path="/home" component={HomePage} />
          <Route exact path="/menu" component={()=><Menu dishes ={this.props.dishes} />} />
          <Route path="/menu/:dishId" component={DishWithId}/>
          <Route exact path="/aboutus" component={() => <AboutPage leaders={this.props.leaders} />} />}/>
          <Route exact path="/contactus" component={Contact}/>
          <Redirect to="/home"/>
       </Switch>
       <Footer/>
      </div>
    );
  }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Main));

DishDetail.js

import React, { Component } from 'react';
import { Card, CardImg, CardImgOverlay, CardText, CardBody, CardTitle, Breadcrumb, BreadcrumbItem , Button, Modal, ModalHeader,ModalBody, Form, FormGroup, Input, Label, Col, Row } from 'reactstrap';
import {Control, LocalForm, Errors} from 'react-redux-form';
import {Link} from 'react-router-dom';

const required = (val) =>val && val.length;
const maxLength = (len) => (val) => !(val) || (val.length <= len);
const minLength = (len) => (val) => val && (val.length >= len);

class DishDetail extends Component{

    constructor(props){
        super(props);
        this.state={
            dish:props.dish,


            isCommentModalOpen: false,

        };


        this.toggleCommentModal=this.toggleCommentModal.bind(this);

    }

    toggleCommentModal(){
        this.setState({
            isCommentModalOpen:!this.state.isCommentModalOpen
        });

    }

    handleSubmit(props,values){

        alert("State" + JSON.stringify(props.addComment(props.dishId, values.rating, values.author, values.comment)));
        // this.state.addComment(this.state.dishId, values.rating, values.author, values.comment)

    }

   render(){
    const RenderDish=({dish})=>{
        return(
                         <Card>

                            <CardImg top src={dish.image} alt={dish.name}/>
                            <CardBody>
                                <CardTitle>{dish.name}</CardTitle>
                                <CardText>{dish.description}</CardText>
                            </CardBody>
                        </Card>
        );
    }


         const RenderComments=({comments})=>{
            const comment_layout= comments.map((comment)=>{
                if(comment.comment!=null){
                   return(
                       <div>

                                    {comment.comment}
                                    {comment.author}, {new Intl.DateTimeFormat('en-US',{year:'numeric',month:'short',day:'2-digit'}).format(new Date(Date.parse(comment.date)))} 

                        </div>   
                   );             

                }else{
                    return(
                        <div></div>
                    );
                }

            });

            return(comment_layout);

        }

         const CommentForm=()=>{
            return(

                    <Button outline onClick={this.toggleCommentModal}>
                            <span className="fa fa-edit fa-lg">Submit Comment</span>
                    </Button>


            );

        }

        if (this.state.dish!==undefined){
        return (
            <div className="container">
            <div className="row">
            <Breadcrumb>

                <BreadcrumbItem>
                    <Link to="/menu">Menu</Link>
                </BreadcrumbItem>
                <BreadcrumbItem active>{this.state.dish.name}
                </BreadcrumbItem>
            </Breadcrumb>
            <div className="col-12">
                <h3>{this.state.dish.name}</h3>
                <hr/>
            </div>
          </div>
            <div className="row ">
                <div className="col-12 col-md-5 m-1">
                    <RenderDish dish={this.state.dish}/>
                </div>
                <div className="col-md-5 col-sm-12 m-1">
                    <h4>Comment</h4>
                        <RenderComments comments={this.props.comments}
                         />
                         <CommentForm/>


                </div>
            </div>
            <Modal isOpen={this.state.isCommentModalOpen} toggle={this.toggleCommentModal}>
                <ModalHeader toggle={this.toggleCommentModal}>
                  Submit Comment                </ModalHeader>
                <ModalBody>
                <div className="col-12">
                        <LocalForm onSubmit={(values)=>this.handleSubmit(this.props,values)}>
                            <Row className="form-group">
                                <Label htmlFor ="rating" md={2}>Rating</Label>

                                    <Control.select model=".rating" id="rating" name="rating" className="form-control">
                                            <option value="1">1</option>
                                            <option value="2">2</option>
                                            <option value="3">3</option>
                                            <option value="4">4</option>
                                            <option value="5">5</option>
                                            <option value="6">6</option>
                                    </Control.select>


                            </Row>
                            <Row className="form-group">
                                <Label htmlFor ="name" md={2}>Name</Label>

                                    <Control.text  model=".name" className="form-control" id="name" name="name" placeholder="name" validators={{required,minLength: minLength(3),maxLength:maxLength(15)}} />
                                    <Errors className="text-danger"
                                    model=".name"
                                    show="touched"
                                    messages={{
                                        required:'Required',
                                        minLength:'Must be greater than 2 char',
                                        maxLength: 'Must be 15 chars or less'
                                    }}
                                    />

                            </Row>

                           <Row className="form-group">
                                <Label htmlFor ="feedback" md={2}>Comment</Label>

                                    <Control.textarea model=".message" className="form-control" id="message" name="message" rows="12" />


                            </Row>
                            <Row className="form-group">

                                    <Button type="submit" color="primary">
                                        Submit
                                    </Button>

                            </Row>
                        </LocalForm>
                    </div>

                </ModalBody>
            </Modal>
            </div>


        );
        }else{
            return(
                <div></div>
            );
        }

}
}

export default DishDetail;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...