如何将值从api调用传递到reducer中的initialState

时间:2019-04-23 19:27:09

标签: reactjs redux

我正在尝试使喜欢帖子成为可能,并允许其更新而无需重新呈现页面。

以下代码允许用户喜欢帖子,但只有刷新后,我才能看到更新的喜欢计数。

喜欢来自映射的帖子数组

像这样

enter image description here

这样的帖子,我得到喜欢的次数likes.length

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

调用此操作后,我如何更新喜欢的次数

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);
        })

    }
}

export const GetPosts = () => {
    return (dispatch, getState) => {
        return Axios.get('/api/posts/myPosts')
            .then( (res) => {
                 const data = res.data
                 const likes = res.data[0].Likes // gets  the first item within array, and shows likes. I would need to get all posts likes not just the first item

                 console.log(likes); // logs data and i can see an array 

                 dispatch({type: GET_POSTS, data})
             })

    }
}

以下代码无效,我必须刷新页面才能看到更新的点赞次数。

我如何将Likes.lenght转换为状态,以便它可以像Like组件那样自动更新onClick?

我确实知道Likes:0不会获得每个帖子的Likes值。我如何才能做到这一点?

减速器

import { 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:
        return {
            ...state, 
            posts: action.data
    }
    case ADD_LIKE:
    console.log(action.id) // renders post id which is 2
    console.log(state.posts) // logs posts array 
        return {
        ...state,
        posts: state.posts.map(post => {
          if (post.id === action.id) {
            return {
              ...post,
              likes: post.likes + 1
            }
          } else return post
        })
      };
      case GET_LIKES_COUNT:
        console.log(action.data) // logs number of likes for all posts
        console.log(state.posts) // logs an array of posts
        console.log(action.id) // logs post id 
        // need to check if post.id is === action.id if so give it the value from action.data

        return({
            ...state,
            likes: action.data
        })

PostItem组件

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); 
        }
    }


    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 style={{ marginLeft: '7px'}} >
                          // gets likes
                          {this.props.likes}  
                       </span>  
                    </span>


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

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

1 个答案:

答案 0 :(得分:1)

在我看来,您的命名存在差异。减速器中的likes用小写的l定义,但是您的代码期望是大写的(根据我在控制台日志和GetPosts操作中所得出的信息)。

case ADD_LIKE:
console.log(action.id) // renders post id which is 2
console.log(state.posts) // logs posts array 
    return {
    ...state,
    posts: state.posts.map(post => {
      if (post.id === action.id) {
        return {
          ...post,
          // likes: post.likes + 1
          Likes: post.Likes + 1
        }
      } else return post
    })
  };