简体   繁体   English

将计数器添加到 redux state

[英]adding counter to redux state

I am trying to add a like increment count using redux to my app, but I am not what I have to do I have been tampering with it for the last few days and have gotten nowhere.我正在尝试使用 redux 向我的应用程序添加一个类似的增量计数,但我不是我必须做的,我在过去几天一直在篡改它,但一无所获。 I wanted to use my comments from my shared folder as the state that I wanted to alter on the store.我想将我的共享文件夹中的评论用作我想在商店中更改的 state。 Any help would be appreciated!任何帮助,将不胜感激! Thanks谢谢

this is my store:这是我的商店:

import { createStore, combineReducers } from 'redux';
import { Comments } from './comments';
import { counterReducer } from './counter'

export const ConfigureStore = () => {
const store = createStore(
    combineReducers({
        counter : counterReducer,
        comments: Comments
    }
));

return store;
};

action creators:动作创建者:

import * as ActionTypes from './ActionTypes';

export const addComment = (commentId, author, text, likes, date) => ({
type: ActionTypes.ADD_COMMENT,
payload: {
    commentId : commentId,
    author: author,
    text: text,
    likes: likes,
    date: date
}
});

export const likeComment = (commentId, likes) => ({
type: ActionTypes.LIKE_COMMENT,
payload: {
    commentId: commentId,
    likes: likes
}
 });

my counter reducer for the likes (i am using my COMMENTS as my state that has the commentId, comments, author, dates, likes):我的计数器减少器(我使用我的评论作为我的 state,它有评论 ID、评论、作者、日期、喜欢):

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


export const counterReducer = (state = COMMENTS, action) => {
switch(action.type) {
    case ActionTypes.LIKE_COMMENT:
        const comment = action.payload
        comment.id = state.length 
        comment.like = state.likes + 1
        return state.concat(comment)
    default:
        return state;
}
};

This is the main component:这是主要组件:

import React, { Component } from 'react';
import TopComment from './TopComment';
import DisplayComment from './PostComment';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { addComment, likeComment } from '../redux/ActionCreators';

const mapStateToProps = state => {
return {
    comments: state.comments,
    likes: state.likes
}
};

const mapDispatchToProps = {
addComment: (commentId, author, text, likes, date) => (addComment(commentId, author, text, 
likes, date)),
likeComment: (likes) => (likeComment(likes))
  }

class Main extends Component{
render(){
    return(
        <div className="comment-box">
            <h1>Join the discussion!</h1>
            <h1>Adam's post:</h1>
            <TopComment/>
            <DisplayComment
            addComment = {this.props.addComment}
            likeComment ={this.props.likeComment}
            comments = {this.props.comments}
            />
        </div>
    )
   }
   }

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

post comment component that will add and display each comment that has been entered through the input:发表评论组件,它将添加并显示通过输入输入的每条评论:

import React, { Component } from 'react';
import { Button, Card, CardBody, CardTitle, CardText } from 'reactstrap';
import { Control, LocalForm, Errors} from 'react-redux-form';

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



// will display comment when posted
function RenderComments({comments}) {

 function handleLike(){
    this.props.likeComment(this.props.likeComment)
 }

 if (comments) {
    return (
        <div className="col-sm-12">
            <h4>Comments</h4>
                {
                    comments.map(comment => {
                        return (
                            <div className="container">
                            <div className="row">
                                <div className="col-sm-12 ">
                                    <Card style={{ 
                                        backgroundColor: '#212d40',
                                        borderColor: '#fff',
                                        borderRadius: '0.25rem',
                                        padding: '0.5rem 0.5rem 0.5rem',
                                        marginBottom: '20px'
                                        }}>
                                        <CardBody>
                                            <img src="./images/random.jpeg" alt="random" height="50px" />
                                            <CardTitle tag="h3">{comment.author}</CardTitle>
                                            <CardText>{comment.text}, <br/>
                                            likes: {comment.likes} <br/>
                                            {new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: '2-digit'}).format(new Date(Date.parse(comment.date)))}
                                            </CardText> <br/>
                                            <Button onClick={handleLike}>Like </Button>
                                        </CardBody>
                                    </Card>
                                </div>
                            </div>
                        </div>
                        );
                    })
                }
        </div>
    );
}
return <div/>;
}

class PostComment extends Component {

handleSubmit(values) {
    this.props.addComment(this.props.commentId, values.author, values.text, values.date);
}

render(){
    return(
        <div>
            <LocalForm className="comment-form" onSubmit={ values => 
      this.handleSubmit(values) }>
                <div className="form-group">
                    <Control.text
                    model=".author"
                    className="form-control" 
                    placeholder="name" 
                    validators={{
                        required, 
                        minLength: minLength(2),
                        maxLength: maxLength(15)
                    }}
                    />
                    <Errors
                    className="text-danger"
                    model=".author"
                    show="touched"
                    component="div"
                    messages={{
                        required: 'Required',
                        minLength: 'Must be at least 2 characters',
                        maxLength: 'Must be 15 characters or less'
                    }}
                    />
                </div>
                <div className="form-group">
                    <Control.text
                    model=".text"
                    className="form-control"
                    placeholder="comment" 
                    />
                </div>
                <Button className="btn-color"  color="primary" type="submit">Submit</Button>
            </LocalForm>
        </div>
    )
}
}

function DisplayComment(props){
 return(
    <div>
        <div className="col">
        <RenderComments 
        addComment = {props.addComment}
        deleteComment =  {props.deleteComment}
        comments = {props.comments}
        likeComment = {props.likeComment}
        />
        </div>
        <div className="col">
        <PostComment
        addComment = {props.addComment}
        comments = {props.comments}
        likeComment= {props.likeComment}
        />
        </div>
    </div>
  )
  }

   export default DisplayComment

this is my commments from my shared file that has all the comment data (likes, comment, date, etc):这是我的共享文件中的评论,其中包含所有评论数据(喜欢、评论、日期等):

export const COMMENTS = [
{
    commentId: 0,
    author: 'Richard',
    text: 'I love disum!',
    likes: 1,
    date: "2020-07-01T19:44Z"
},
{
    commentId: 1,
    author: 'Jake Paul',
    text: 'Fried foods are the best!',
    likes:  0,
    date: "2020-09-20T19:44Z"
}
]

You're mixing the source of truth for comment likes.您正在混合评论喜欢的真相来源。 Should the likes count be part of the comment?点赞数应该成为评论的一部分吗? Or should it be it's own thing?还是应该是自己的东西?

Let's KISS and just keep the likes count as part of the comment as you have already set up - get rid of your other counter reducer altogether.让我们亲吻并保持喜欢作为评论的一部分,就像你已经设置的那样 - 完全摆脱你的其他计数器减速器。

Your comments reducer should now look like this:您的评论减速器现在应该如下所示:

  switch(action.type) {
    case ActionTypes.ADD_COMMENT:
        // your existing code to handle adding a comment to your state

    // this new case increments the likes for a given comment
    case ActionTypes.LIKE_COMMENT:
        return state.comments.map(c => c.commentId === action.payload.commentId ? ({ ...c,likes: c.likes+1 }) : c);
    default:
        return state;
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM