React-Redux:删除项目时无法读取未定义的属性“ map”

时间:2018-08-17 14:42:37

标签: reactjs redux react-redux

点击删除按钮后出现错误:

  

无法读取未定义的属性“地图”。

我是React Redux JS的新手。

请在下面查看我的组件缩减器和操作的代码:

Post.js

class Post extends Component {
  constructor(){
    super();
    this.deletePost = this.deletePost.bind(this);
  }

  deletePost(postId){
    this.props.deletePost(postId);
  }

  render(){
    const postItems = this.props.posts.map(post => (
        <div key={post.id} className="row">
            <div className="container">
                <h3>{post.title}</h3>
                <p>{post.body}</p>
                <button
                    onClick={() =>this.deletePost(post.id)}
                    className="btn btn-danger">
                    Delete
                </button>
            </div>
        </div>  
    ))

    const divStyle = {
        padding: '15px',
    }

    return (
        <div style={divStyle}>
            <PostForm />
            <hr/>
            {postItems}
        </div>
    )
  }
}
const mapStateToProps = state => ({
    posts: state.posts.items,
    newPost: state.posts.item
}) 

export default connect(mapStateToProps, { fetchPosts, deletePost })(Post);

PostAction.js (这是我的删除操作。我正在使用jsonplaceholder API发布。)

export const deletePost = (postId) => dispatch => {
   fetch('https://jsonplaceholder.typicode.com/posts/'+postId, {
    method: 'DELETE',
  })
  .then(dispatch({
    type: DELETE_POST,
    payload: postId
  }));
}

PostReducer.js (这是我的减速器。)

case DELETE_POST:{
     const newState = Object.assign([], state);`enter code here`

     const filteredItems = newState.items.filter(items => {
          return items.id != action.payload;
     });

     return filteredItems;
}

2 个答案:

答案 0 :(得分:1)

case DELETE_POST:{
 const { items } = state;
 const filteredItems = items.filter(items => {
      return items.id != action.payload;
 });

 return { 
    ...state,
    items: [ ...filteredItems ]
 };

}

答案 1 :(得分:0)

是的,只需替换

return filteredItems; to  return { items: filteredItems }

但是请检查我的代码是否正确。谢谢