删除帖子后,组件不呈现更新状态

时间:2020-04-06 07:15:54

标签: reactjs redux react-redux

我在删除应用中的帖子时遇到了一些问题。因此,删除帖子后,状态应更新,组件应重新渲染,对吗?因此,删除我的帖子后,组件将使用相同的数据重新渲染。如果刷新,则页面上仅显示更新的数据。例如,如果删除一个帖子时我的应用程序中有3个帖子,则该组件会重新呈现,但仍显示3个帖子。我不知道为什么会这样。

这是我的代码。

UserFeed

import React, { Component } from "react"
import { getUserPosts, getCurrentUser } from "../actions/userActions"
import { connect } from "react-redux"
import Cards from "./Cards"

class UserFeed extends Component {

  componentDidMount() {
    const authToken = localStorage.getItem("authToken")
    if (authToken) {
      this.props.dispatch(getCurrentUser(authToken))
      if (this.props && this.props.userId) {
        this.props.dispatch(getUserPosts(this.props.userId))
      } else {
        return null
      }
    }
  }

  render() {
    console.log("render called")
    const { isFetchingUserPosts, userPosts } = this.props
    console.log(isFetchingUserPosts, userPosts)
    return isFetchingUserPosts ? (
      <p>Fetching....</p>
    ) : (
      <div>
        {userPosts &&
          userPosts.map(post => {
            return <Cards key={post._id} post={post} />
          })}
      </div>
    )
  }
}

const mapStateToPros = state => {
  return {
    isFetchingUserPosts: state.userPosts.isFetchingUserPosts,
    userPosts: state.userPosts.userPosts.userPosts,
    userId: state.auth.user._id
  }
}

export default connect(mapStateToPros)(UserFeed)

Cards

import React, { Component } from "react"
import { connect } from "react-redux"
import { deletePost } from "../actions/userActions"

class Cards extends Component {

  handleDelete = (_id) => {
    this.props.dispatch(deletePost(_id))
  }

  render() {
    const { _id, title, description } = this.props.post
    return (
      <div className="card">  
        <div className="card-content">
          <div className="media">
            <div className="media-left">
              <figure className="image is-48x48">
                <img
                  src="https://bulma.io/images/placeholders/96x96.png"
                  alt="Placeholder image"
                />
              </figure>
            </div>
            <div className="media-content" style={{border: "1px grey"}}>
              <p className="title is-5">{title}</p>
              <p className="content">{description}</p>
              <button onClick={() => {this.handleDelete(_id)}} className="button is-success">Delete</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}


const mapStateToProps = state => {
  return state
}

export default compose(withRouter, connect(mapStateToProps))(Cards)

deletePost操作

export const deletePost = (id) => {
  return async dispatch => {
    dispatch({ type: "DELETING_POST_START" })
    try {
      const res = await axios.delete(`http://localhost:3000/api/v1/posts/${id}/delete`)
      dispatch({
        type: "DELETING_POST_SUCCESS",
        data: res.data
      })
    } catch(error) {
      dispatch({
        type: "DELETING_POST_FAILURE",
        data: { error: "Something went wrong" }
      })
    }
  }
}

userPosts减速器

const initialState = {
    isFetchingUserPosts: null,
    isFetchedUserPosts: null,
    userPosts: [],
    fetchingUserPostsError: null,
    isDeletingPost: false,
    isDeletedPost: false,
    deletingError: false,
  }

  const userPosts = (state = initialState, action) => {
    switch (action.type) {
      case "FETCHING_USER_POSTS_START":
        return {
          ...state,
          isFetchingUserPosts: true,
          fetchingUserPostsError: null,
        }
      case "FETCHING_USER_POSTS_SUCCESS":
        return {
          ...state,
          isFetchingUserPosts: false,
          isFetchedUserPosts: true,
          userPosts: action.data,
          fetchingUserPostsError: null,
        }
      case "FETCHING_USER_POSTS_ERROR":
        return {
          ...state,
          isFetchingUserPosts: false,
          isFetchedUserPosts: false,
          fetchingUserPostsError: action.data.error,
        }
      case "DELETING_POST_START":
        return {
          ...state,
          isDeletingPost: true,
          deletingError: null,
        }
      case "DELETING_POST_SUCCESS":
        const filteredPostList = state.postList.filter((post) => post._id !== action.data._id)
        return {
          ...state,
          isDeletingPost: false,
          isDeletedPost: true,
          userPosts: filteredPostList,
          deletingError: null,
        }
      case "DELETING_POST_ERROR":
        return {
          ...state,
          isDeletingPost: false,
          deletingError: action.data.error,
        }
      default:
        return state
    }
  }

  export default userPosts

1 个答案:

答案 0 :(得分:0)

删除后操作需要在成功后将id传递给减速器。

删除帖子操作

export const deletePost = (id) => {
  return async dispatch => {
    dispatch({ type: "DELETING_POST_START" })
    try {
      const res = await axios.delete(`http://localhost:3000/api/v1/posts/${id}/delete`)
      dispatch({
        type: "DELETING_POST_SUCCESS",
        data: res.data,
        id
      })
    } catch(error) {
      dispatch({
        type: "DELETING_POST_FAILURE",
        data: { error: "Something went wrong" }
      })
    }
  }
}

访问用户帖子精简程序中的action.id

case "DELETING_POST_SUCCESS":
  return {
    ...state,
    isDeletingPost: false,
    isDeletedPost: true,
    userPosts: state.postList.filter(post => post._id !== action.id),
    deletingError: null,
  }