当前位置: 首页 > 知识库问答 >
问题:

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

公羊瀚
2023-03-14

我试图获取一个基于post.id的计数,该计数等于action.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  
    }
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})
             })

    }
}
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个答案

陶星渊
2023-03-14

您试图获取一个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

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

 类似资料: