首页 > 解决方案 > 单击时 Redux 状态计数未更新

问题描述

调用此操作时,我正在尝试将更新计数增加 + 1。因此,例如一个喜欢有 89 个喜欢 + 1 将使它成为 90

以下代码使我点击喜欢时点赞数消失。

像这样

在此处输入图像描述

在此处输入图像描述

我的目标是在单击后将初始值提高 1。

减速器

const initialState = {
    post: [],
    postError: null,
    posts:[],
    isEditing:false,
    isEditingId:null,
    likes:0,
    postId:null
}

export default (state = initialState, action) => {
    switch (action.type) {
    case ADD_LIKE:
    console.log(action.id) // renders post id which is 2
    console.log(state.posts) // logs posts array
    console.log(state.posts)
        return {
        ...state,
        posts: state.posts.map(post => {
          if (post.id === action.id) {
                post.Likes.map( (like) => {
                    console.log(like);
                })
            } 
            return {
                ...post,
                ...post.Likes ,
                Likes: post.Likes.length + 1
            }  


        })
      }; 

喜欢在这样的对象内

在此处输入图像描述

console.log(like);

呈现这个

在此处输入图像描述

动作.js

export const postLike = (id) => {
    return (dispatch) => {
        // console.log(userId);
        return Axios.post('/api/posts/like', {
            postId: id
        }).then( (like) => {

            dispatch({type: ADD_LIKE, id})
                // console.log('you have liked this', like)
        }).catch( (err)=> {
                console.log('there seem to be an error', err);
        })

    }
}

像组件

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCoffee, faAdjust } from '@fortawesome/free-solid-svg-icons';
import {connect} from 'react-redux';
import {  postLike} from '../actions/';
class Like extends Component{
    constructor(props){
        super(props);
        this.state = {
            likes: null,
            heart: false
        }
    }

    clickLike = (id) => {
        this.props.postLike(id);
        // toggles between css class
        this.setState({
            heart: !this.state.heart
        })
    }
    render(){
       return(
            <div style={{float:'right', fontSize: '1.5em', color:'tomato'}} >
            <i style={{ marginRight: '140px'}} className={this.state.heart ? 'fa fa-heart':'fa fa-heart-o' }>
                    <span style={{ marginLeft: '6px'}}>
                        <a href="#" onClick={() =>this.clickLike(this.props.like)}>Like</a>   

                    </span>
                    {/* gets the like counts */}
                    <span style={{ marginLeft: '7px'}} >{this.props.likes}  </span>  

                </i>
            </div>       
       )
    }
}
const mapStateToProps = (state) => ({
    isEditingId: state.post.isEditingId,
})
const mapDispatchToProps = (dispatch) => ({

    postLike: (id) => dispatch( postLike(id))
    // Pass id to the DeletePost functions.
});
export default connect(mapStateToProps, mapDispatchToProps)(Like);

这里传入like组件

喜欢<Like like={id} likes={Likes.length} />

PostItem.js

import React, { Component } from 'react';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import moment from 'moment';
import Editable from './Editable';
import {connect} from 'react-redux';
import {UpdatePost, postLike} from '../actions/';
import Like from './Like';
import Axios from '../Axios';
const Styles = {
    myPaper: {
        margin: '20px 0px',
        padding: '20px'
    },
    button:{
        marginRight:'30px'
    }
}
class PostItem extends Component{
    constructor(props){
        super(props);
        this.state = {
            disabled: false,
            myId: 0,
            likes:0
        }
    }
    onUpdate = (id, title) => () => {
        // we need the id so expres knows what post to update, and the title being that only editing the title. 
        if(this.props.myTitle !== null){
            const creds = {
                id, title
            }
            this.props.UpdatePost(creds); 
        }
    }

    getLikes = (id) =>  {
        this.props.getLikeCount(id)
    }
    render(){
        const {title, id, userId, removePost, createdAt, post_content, username, editForm, isEditing, editChange, myTitle, postUpdate, Likes, clickLike} = this.props
        return(
            <div>

                   <Typography variant="h6" component="h3">
                   {/* if else teneray operator */}
                   {isEditing ? (
                          <Editable editField={myTitle ? myTitle : title} editChange={editChange}/>
                   ): (
                       <div>
                           {title}
                       </div>    
                   )}         
                   </Typography>
                   <Typography component="p">
                       {post_content}
                       <h5>
                           by: {username}</h5>
                       <Typography color="textSecondary">{moment(createdAt).calendar()}</Typography>
                       <Like like={id} likes={Likes.length} />
                   </Typography>
                   {!isEditing ? (
                       <Button variant="outlined" type="submit" onClick={editForm(id)}>
                           Edit
                       </Button>
                   ):(     
                       // pass id, and myTitle which as we remember myTitle is the new value when updating the title
                        <div>
                            <Button 
                                disabled={myTitle.length <= 3}
                                variant="outlined" 
                                onClick={this.onUpdate(id, myTitle)}>
                                Update
                            </Button>
                            <Button 
                                variant="outlined" 
                                style={{marginLeft: '0.7%'}}
                                onClick={editForm(null)}>
                                Close
                            </Button>
                        </div>
                   )}
                   {!isEditing && (
                    <Button
                        style={{marginLeft: '0.7%'}}
                        variant="outlined"
                        color="primary"
                        type="submit"
                        onClick={removePost(id)}>
                        Remove
                    </Button>
                    )}
           </div>
       )
    }
}
const mapStateToProps = (state) => ({
    isEditingId: state.post.isEditingId
})
const mapDispatchToProps = (dispatch) => ({
    // pass creds which can be called anything, but i just call it credentials but it should be called something more 
    // specific.
    UpdatePost: (creds) => dispatch(UpdatePost(creds)),
    postLike: (id) => dispatch( postLike(id))
    // Pass id to the DeletePost functions.
});
export default connect(null, mapDispatchToProps)(PostItem);

标签: reactjsreduxreact-redux

解决方案


你有几个问题:

  • InitialState 您定义likes但在减速器中您正在更新Likes为计数器

  • <Like />你传递一个名为的道具likes,它来自Likes.length. Likes是传递给您的组件的道具PostItem。所以错误可能在这里,检查来源,Likes如果它不是一个数组,你的调用 Likes.length将返回undefined使你的计数器“消失”的原因


推荐阅读