未处理的拒绝(TypeError):比较ID时无法读取未定义的属性”

时间:2019-04-26 14:44:07

标签: reactjs redux react-redux

我正在尝试获取一个基于post.id的计数,该计数等于action.id

 console.log(action.data.find((post) => post.id === action.id).Likes.length)

但是我得到了这个

  

未处理的拒绝(TypeError):无法读取的属性“喜欢”   未定义

但是当我将其更改为

action.data.find((post) => post.id === 5).Likes.length) // 5 is an id of an existing post.

它可以按预期工作,但是它必须是动态的。

这是减速器

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

export default (state = initialState, action) => {
    switch (action.type) {
      case GET_POSTS:
      console.log(action.data)
      console.log(action.data.find((post) => post.id === action.id).Likes.length) // fetchs likes count according to post.id but needs to be dynamic
        return {
            ...state, 
            posts: action.data, // maps posts fine,
            likes: action.data.find((post) => post.id === action.id).Likes.length 
            // needs to be dynamic so i can multiple post.ids  
    }

Actions.js

export const GetPosts = () => {
    return (dispatch, getState) => {
        return Axios.get('/api/posts/myPosts')
            .then( (res) => {
                 const data = res.data       
                 const id = data.map( (post) => post.id)  // gets posts id [5,3]
                 dispatch({type: GET_POSTS, data, id})
             })

    }
}

Posts.js

import React, { Component } from 'react';
import PostList from './PostList';
import {connect} from 'react-redux';
import { withRouter, Redirect} from 'react-router-dom';
import {GetPosts} from '../actions/';
const Styles = {
    myPaper:{
      margin: '20px 0px',
      padding:'20px'
    }
    , 
    wrapper:{
      padding:'0px 60px'
    }
}
class Posts extends Component {
  state = {
    posts: [],
    loading: true,
    isEditing: false, 
  }
  async componentWillMount(){
    await this.props.GetPosts();

    const thesePosts = await this.props.myPosts
    const myPosts2 = await thesePosts
    this.setState({
      posts: myPosts2,
      loading:false
    })

    console.log(this.state.posts.Likes);
  }


  render() {
    const {loading} = this.state;
    const { myPosts} = this.props
    if (!this.props.isAuthenticated) {
      return (<Redirect to='/signIn' />);
    }
    if(loading){
      return "loading..."
    }
    return (
      <div className="App" style={Styles.wrapper}>
        <h1> Posts </h1>
        <PostList posts={this.state.posts}/>
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,
  myPosts: state.post.posts
})
const mapDispatchToProps = (dispatch, state) => ({
  GetPosts: () => dispatch( GetPosts())
});
export default withRouter(connect(mapStateToProps,mapDispatchToProps)(Posts));

PostList.js

    render(){
        const {posts} = this.props;
        return (
            <div>
                {posts.map((post, i) => (

                    <Paper key={post.id} style={Styles.myPaper}>

                    {/* {...post} prevents us from writing all of the properties out */}
                        <PostItem  
                        // or put this.state.likes in the myLikes prop
                             myLikes={this.props.myLikes}                 
                             myTitle={this.state.title} 
                             editChange={this.onChange} 
                             editForm={this.formEditing} 
                             isEditing={this.props.isEditingId === post.id} 
                             removePost={this.removePost} 
                             {...post} 
                        />
                    </Paper>
                ))}
            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:1)

您正在尝试获取ID不存在的帖子。

查看how .find会成功,如果什么都没找到,它将返回undefined

因此,当您执行action.data.find((post) => post.id === action.id)时,找不到与post具有相同ID的任何action,并且它返回undefined并且您无法获得{ Like中的{1}}。

我建议在访问undefined

之前先进行检查
.Like

我知道这个答案并不能解决您的问题,但是它可以说明问题所在以及解决方法,希望您能更好地了解问题的所在并为您解决问题。