Reactjs 单击时,Redux状态计数未更新

Reactjs 单击时,Redux状态计数未更新,reactjs,redux,react-redux,Reactjs,Redux,React Redux,调用此操作时,我正在尝试更新计数增量+1。例如,一个like有89个likes+1将使其成为90 下面的代码使我单击like时like计数消失 像这样 我的目标是使初始值在单击后由1向上投票。 减速器 const initialState = { post: [], postError: null, posts:[], isEditing:false, isEditingId:null, likes:0, postId:null }

调用此操作时,我正在尝试更新计数增量+1。例如,一个like有89个likes+1将使其成为90

下面的代码使我单击like时like计数消失

像这样

我的目标是使初始值在单击后由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)

呈现这个

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 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);
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);
类似组件

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);
import React,{Component}来自'React';
从“react dom”导入react dom
从'@fortawesome/react fontawesome'导入{FontAwesomeIcon};
从“@fortawesome/free solid svg icons”导入{faCoffee,faAdjust};
从'react redux'导入{connect};
从“../actions/”导入{postLike};
类扩展组件{
建造师(道具){
超级(道具);
此.state={
喜欢:空,
心脏:假
}
}
clickLike=(id)=>{
this.props.postLike(id);
//在css类之间切换
这是我的国家({
心脏:!这个。状态。心脏
})
}
render(){
返回(
{/*获取类似的计数*/}
{this.props.likes}
)
}
}
常量mapStateToProps=(状态)=>({
isEditingId:state.post.isEditingId,
})
const mapDispatchToProps=(调度)=>({
postLike:(id)=>dispatch(postLike(id))
//将id传递给DeletePost函数。
});
导出默认连接(mapStateToProps、mapDispatchToProps)(类似);
like组件在这里传递

positem.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 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);
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);
import React,{Component}来自'React';
从“@material ui/core/Paper”导入纸张;
从“@material ui/core/Button”导入按钮;
从“@material ui/core/Typography”导入排版;
从“力矩”中导入力矩;
从“./Editable”导入可编辑文件;
从'react redux'导入{connect};
从“../actions/”导入{UpdatePost,postLike};
从“./Like”导入Like;
从“../Axios”导入Axios;
常量样式={
我的论文:{
保证金:“20px 0px”,
填充:“20px”
},
按钮:{
marginRight:'30px'
}
}
类PostItem扩展组件{
建造师(道具){
超级(道具);
此.state={
残疾人士:错,,
myId:0,
喜欢:0
}
}
onUpdate=(id,标题)=>()=>{
//我们需要id,以便expres知道要更新什么帖子,而标题只是编辑标题。
if(this.props.myTitle!==null){
常数信度={
身份证
}
这个.props.UpdatePost(creds);
}
}
getLikes=(id)=>{
this.props.getLikeCount(id)
}
render(){
const{title,id,userId,removePost,createdAt,post_content,username,editForm,isEditing,editChange,myTitle,postapdate,Likes,clickLike}=this.props
返回(
{/*if-else-teneray操作符*/}
{i编辑(
): (
{title}
)}         
{post_content}
收件人:{username}
{时刻(createdAt).calendar()}
{!我正在编辑(
编辑
):(     
//passid和myTitle,我们记得myTitle是更新标题时的新值
({
isEditingId:state.post.isEditingId
})
const mapDispatchToProps=(调度)=>({
//传递可以被称为任何东西的信条,但我只是称之为凭证,但它应该被称为更多的东西
//具体的。
UpdatePost:(creds)=>调度(UpdatePost(creds)),
postLike:(id)=>dispatch(postLike(id))
//将id传递给DeletePost函数。
});
导出默认连接(null,mapDispatchToProps)(PostItem);

问题是您正在操作中进行异步调用。千万不要这样做。使用诸如redux saga或redux thunk之类的框架进行异步调用。

您有几个问题:

  • 初始状态定义了
    likes
    ,但在减速机中,将
    likes
    更新为计数器

  • 中,您正在传递一个名为
    likes
    的道具,该道具来自
    likes。length
    likes
    是传递给组件
    positem
    的道具。因此错误可能在这里,请检查
    likes
    的来源,因为它不是您调用的数组
    likes。length
    将返回
    unde罚款
    是什么让您的计数器“消失”


将减速机更改为此,这将使类似计数正常工作

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
    }
}
在post item组件上像这样更改组件

 <Like like={id}/> 

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

我明白你的意思,除此之外,代码对你来说还不错吗?但我使用的是redux thunk,它在我的商店中配置。抱歉,没有意识到。我以前使用过thunk,但现在切换到了我发现了一些问题。但可能还需要帮助。我将发布答案。如果你能看到他们的答案,请检查下面的答案,这将是一个改进的方法。