阵列中所有项目的Redux更新状态

时间:2019-04-22 12:09:01

标签: reactjs redux

当从reducer调用ADD_LIKE时,我试图告诉react / redux投票给likeCount。

但是,它对所有帖子项目

使用的编号

我该怎么做。

if(action.id === post.id)然后执行likes: state.likes + 1

这样,它只能投票支持该帖子。

case ADD_LIKE:
    // console.log(action.id)
    return({
        ...state,
        likes: state.likes + 1
    })

Actions.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 { ADD_LIKE, GET_LIKES_COUNT} 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_LIKES_COUNT:
            // console.log(action.data)
            return({
                ...state,
                likes:action.data
            })
         case ADD_LIKE:
            // console.log(action.id)
            return({
              ...state,
            likes: state.likes + 1
          })
        default:
            return state
    }
}

类似组件

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 {  getLikeCount, postLike} from '../actions/';
class Like extends Component{
    constructor(props){
        super(props);
        this.state = {
            likes: null,
            heart: false
        }
    }
    // dont remove () after (id) or else infinite onClick
    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 */}
                    {this.props.likeCount}
                </i>
            </div>       
       )
    }
}
const mapStateToProps = (state) => ({
    isEditingId: state.post.isEditingId,
    likeCount:state.post.likes
})
const mapDispatchToProps = (dispatch) => ({
    getLikeCount: (id) => dispatch(getLikeCount(id)),
    postLike: (id) => dispatch( postLike(id))
    // Pass id to the DeletePost functions.
});
export default connect(mapStateToProps, mapDispatchToProps)(Like);

<Like like={id}/>的帖子ID为id,并作为道具传递

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, getLikeCount, 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,
        }
    }
    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); 
        }
    }
    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}/>
                   </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)),
    getLikeCount: (id) => dispatch(getLikeCount(id)),
    postLike: (id) => dispatch( postLike(id))
    // Pass id to the DeletePost functions.
});
export default connect(null, mapDispatchToProps)(PostItem);

PostList.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 {connect} from 'react-redux';
import {DeletePost,  getLikeCount, postLike, UpdatePost,EditChange, DisableButton} from '../actions/';
import PostItem from './PostItem';
const Styles = {
    myPaper: {
        margin: '20px 0px',
        padding: '20px'
    }
}
class PostList extends Component{
    constructor(props){
        super(props);
        this.state ={
            title: '',
        }
    }
    // Return a new function. Otherwise the DeletePost action will be dispatch each
     // time the Component rerenders.
    removePost = (id) => () => {
        this.props.DeletePost(id);
    }
    onChange = (e) => {
        e.preventDefault();
        this.setState({
            title: e.target.value
        })
    }
    formEditing = (id) => ()=> {;
        this.props.EditChange(id);
    }
    getLikes = (id) =>  {
        // console.log(id);
        this.props.getLikeCount(id)
        console.log(this.props.likeCount)
    }
    render(){
        const {posts} = this.props;
        return (
            <div>
                {posts.map((post, i) => (
                    <Paper key={post.id} style={Styles.myPaper}>
                     {this.getLikes(post.id)}
                    {/* {...post} prevents us from writing all of the properties out */}
                        <PostItem
                             myTitle={this.state.title} 
                             editChange={this.onChange} 
                             editForm={this.formEditing} 
                             isEditing={this.props.isEditingId === post.id} 
                             removePost={this.removePost} 
                             {...post} 
                        />
                    </Paper>
                ))}
            </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.
    EditChange: (id) => dispatch(EditChange(id)),
    UpdatePost: (creds) => dispatch(UpdatePost(creds)),
    getLikeCount: (id) => dispatch(getLikeCount(id)),
    postLike: (id) => dispatch( postLike(id)),
    // Pass id to the DeletePost functions.
    DeletePost: (id) => dispatch(DeletePost(id))
});
export default connect(mapStateToProps, mapDispatchToProps)(PostList);

编辑

Actions.js

export const getLikeCount = (id) => {
    return (dispatch, getState) => {
        return Axios.get(`/api/posts/likes/count/${id}`)
            .then( (res) => {
                 const data = res.data
                 console.log(data); // logs data and i can see an array 
                 dispatch({type: GET_LIKES_COUNT, data})
             })

    }
}

{this.props.likeCount}日志

enter image description here

enter image description here

我尝试这样做

case ADD_LIKE:
    return {
    ...state,
    posts: state.posts.map(post => {
      if (post.id === action.id) {
        return {
          ...post,
          likes: post.likes + 1
        }
      } else return post
    })
  };

但由于某些原因它不会更新点赞数。

2 个答案:

答案 0 :(得分:1)

我不确定您的代码如何工作,但我认为Like组件就像每个帖子的爱情图标一样?但是从您的代码来看,似乎所有Like组件都共享相同的Redux状态post.likes

const mapStateToProps = (state) => ({
    isEditingId: state.post.isEditingId,
    likeCount:state.post.likes
})

这就是为什么所有Like拥有相同的喜欢计数的原因。我建议重组您的redux状态,例如将点赞数放入post对象,例如:

减速器

import { ADD_LIKE, GET_LIKES_COUNT} from '../actions/';

const initialState = {
    post: [],
    postError: null,
    posts:[], // put likes count in post item, for eg { id: number, likes: number }
    isEditing:false,
    isEditingId:null,
    postId:null
}

export default (state = initialState, action) => {
    switch (action.type) {
         case ADD_LIKE:
            return({
              ...state,
            posts: state.posts.map(post => (post.id === action.id ? { ...post, likes: post.likes + 1 } : post))
          })
        default:
            return state
    }
}

然后,与其在Like组件中使用Redux,不如从PostItem传递数据,将更易于维护:

PostItem

render() {
    return (
        ....
        <Like likeCount={post.likes} onClick={() => this.onClick(post.id)} />
        ....
    )
}

答案 1 :(得分:0)

尝试一下, 您的意思是post.id而不是您所在州的postId。因为您无法比较if(action.id === post.id),所以喜欢:state.likes + 1这样,因为post是数组。

如果您错误地使用了post.id而不是postId,则可以尝试以下解决方案

export default (state = initialState, action) => {
    switch (action.type) {
        case GET_LIKES_COUNT:
            // console.log(action.data)
            return({
                ...state,
                likes:action.data
            })
         case ADD_LIKE:
            // console.log(action.id)
            return({
              ...state,
            likes: action.id === state.postId? state.likes + 1 : state.likes
          })
        default:
            return state
    }
}