未处理的拒绝(类型错误):比较 id 时无法读取未定义的属性



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

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

然而我得到这个

未处理的拒绝(类型错误(:无法读取属性"喜欢" 定义

但是当我改变它时,

就像
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  
    }

操作.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})
             })
    }
}

帖子.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));

帖子列表.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>
        )
    }
}

您正在尝试获取一个 id 不存在的帖子。

查看.find的工作方式,如果未找到任何内容,它将返回undefined

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

我建议在访问.Like之前检查一下

let post = action.data.find((post) => post.id === action.id)
let likeLen = post ? post.Likes.length : somethingYouWant

我知道这个答案并不能解决你的问题,但它显示了问题是什么以及如何解决它,我希望你能更好地了解正在发生的事情并帮助你解决问题。

最新更新