单击时Redux状态计数未更新

时间:2019-04-24 15:26:34

标签: reactjs redux react-redux

我正在尝试在调用此操作时将更新计数增加1。例如,一个赞有89个赞+ 1个将变成90个

下面的代码,使点击计数消失。

像这样

enter image description here

enter image description here

我的目标是使点击后的初始值增加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
            }  


        })
      }; 

喜欢在这样的对象中

enter image description here

console.log(like);

提供此

enter image description here

Action.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);

3 个答案:

答案 0 :(得分:1)

您有几个问题:

  • 您定义了likes的InitialState,但是在化简器中您正在将Likes更新为计数器

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

    < / li>

答案 1 :(得分:0)

问题在于您正在操作内进行异步调用。绝对不要那样做。使用redux-saga或redux-thunk之类的框架进行异步调用。

答案 2 :(得分:0)

将reducer更改为该值,即可获得类似计数。

import { POST_FAIL, GET_POSTS, EDIT_POST, DISABLED,  ADD_LIKE,} from '../actions/';

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

export default (state = initialState, action) => {
    switch (action.type) {
        case GET_POSTS:
            console.log(action.data[0].Likes.length)
            return {
                ...state, 
                posts: action.data,
                // set likes to but it only gets the first post, when it should get all posts
                likes:action.data[0].Likes.length
        }


        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,
            likes: state.likes + 1
            };

        default:
            return state
    }
}

在帖子项目组件上像这样更改组件

 <Like like={id}/> 

{this.props.myLikes}将在减速器中设置喜欢的对象。

Like.js

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.myLikes}  </span>  

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

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

现在,这越来越接近最终解决方案了,他们需要一种映射喜欢的方式,因此并非所有帖子都是第一个喜欢的帖子的价值