【问题标题】:Unhandled Rejection (TypeError): Cannot read property '' of undefined when comparing id未处理的拒绝(TypeError):比较 id 时无法读取未定义的属性“”
【发布时间】:2019-04-26 14:44:06
【问题描述】:

我正在尝试获取基于等于 action.idpost.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>
        )
    }
}

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您正在尝试使用不存在的 id 获取帖子。

    查看how .find 有效,如果没有找到,它将返回undefined

    因此,当您执行action.data.find((post) =&gt; 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
    

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

    【讨论】:

    • 谢谢你的理解。将多次引用。
    猜你喜欢
    • 2019-07-19
    • 1970-01-01
    • 2019-01-24
    • 2021-01-13
    • 2019-04-07
    • 2019-06-03
    • 2020-04-09
    • 2019-11-13
    • 2021-10-19
    相关资源
    最近更新 更多