尝试删除所选ID时有效载荷未定义?

时间:2019-03-26 13:07:55

标签: reactjs redux

当我获取并添加数据时,有效负载没有问题,但是当ı删除项目时没有错误,但是没有从列表中删除什么?我发疯了,我是React和Redux的新手,尝试学习新的东西,我在网上检查了其他PPL所做的事情,但是找不到解决方案,谢谢您的帮助。 如果还可以给我展示updatePost的方法,我应该怎么走?单击更新图标时,使用模式

打开模式
import { FETCH_POSTS, NEW_POST, DEL_POST } from '../actions/types';

const initialState = {
  items: [],
  item: {}
};

export default function (state = initialState, action) {
  console.info('POST reducer running', action)
  switch (action.type) {
    case FETCH_POSTS:
      return {
        ...state,
        items: action.payload
      };
    case NEW_POST:
      return {
        ...state,
        item: action.payload
      };
    case DEL_POST:
      return Object.assign({}, state, {
        items: console.info('DEL_POST postReducer: ', state),
        items: [...state.items.filter(item => item.id !== action.id)],
      });
    // return state.filter(post => post.id !== action.id)

    default:
      return state;
  }
}

//postActions.js

export const deletePost = id => dispatch => {
  console.info('deletePost dispatch: ', dispatch)
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: 'DELETE',
  })
    .then(res => console.info('deletePost response: ', res))
    .then(id =>
      dispatch({
        type: DEL_POST,
        payload: id
      })
    )
}


/Post.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { fetchPosts, deletePost } from '../../actions/postActions';

class Posts extends Component {
  componentWillMount() {
    this.props.fetchPosts();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.newPost) {
      this.props.posts.unshift(nextProps.newPost);
    }
  }

  onDeleteClick = id => {
    console.info('deleted id clicked', id)
    this.props.deletePost(id)
  }

  render() {
    const postItems = this.props.posts.map(post => (
      <tr key={post.id}>
        <td>{post.title}</td>
        <td>{post.body}</td>
        <td>
          <i class="fas fa-trash"
            style={icon}
            onClick={() => this.onDeleteClick(post.id)}
            title="Delete"
          />
          <i class="fas fa-edit"
            style={icon}
            onClick={this.onUpdateClick}
            title="Edit"
          />
        </td>
      </tr>
    ));
    if (!postItems) {
      return (
        <div>
          nothing found...
        </div>
      )
    }
    return (
      <div>
        <table class="table">
          <thead>
            <tr>
              <th scope="col">Title</th>
              <th scope="col">Body</th>
              <th scope="col">Process</th>
            </tr>
          </thead>
          <tbody>{postItems}</tbody>
        </table>
      </div>
    );
  }
}

const icon = {
  padding: "5px",
  cursor: "pointer"
}

Posts.propTypes = {
  fetchPosts: PropTypes.func.isRequired,
  deletePost: PropTypes.func.isRequired,
  posts: PropTypes.array.isRequired,
  // newPost: PropTypes.object
};

const mapStateToProps = state => ({
  posts: state.posts.items,
  newPost: state.posts.item
});


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

2 个答案:

答案 0 :(得分:0)

我认为您在这里犯了一些错误:

  • 将状态包含在Object.assign
  • 您写了action.id而不是action.payload.id
  • Array.filter(已创建新数组)上使用扩展运算符
  • 忘记在返回的商品中包含商品(如果有意,请忽略此评论)

在减速器中使用它,它应该可以正常工作。

     case DEL_POST:
      return Object.assign({}, {
        items: state.items.filter(item => item.id !== action.payload.id),
        item: state.item,
      });

此外,我强烈建议您不要在reducer内直接记录任何内容。

答案 1 :(得分:0)

我认为在DEL_POST的过滤器方法中,它应该为item.id !== action.payload,而您有item.id !== action.id。调度id操作时,您以payload的值传递了DEL_POST

 export default function (state = initialState, action) {
    console.info('POST reducer running', action)
    switch (action.type) {
        case FETCH_POSTS:
            return {
                ...state,
                items: action.payload
            };
        case NEW_POST:
            return {
                ...state,
                item: action.payload
            };
        case DEL_POST:
            return {
                ...state,
                items: state.items.filter(item => item.id !== action.payload)
            }
        default:
            return state;
    }
}


export const deletePost = id => dispatch => {
    console.info('deletePost dispatch: ', dispatch)
    return fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
        method: 'DELETE',
    })
        .then(res => {
            console.info('deletePost response: ', res)
            dispatch({
                type: DEL_POST,
                payload: id
            })
        })
}