状态未使用 Redux 更新

State not updating with Redux

我正在尝试使用 Redux 删除 post,但是当我这样做时状态没有更新,只有当我重新加载页面时我才能删除随后显示的帖子。

请在此处查看 App.js 组件...

import React from 'react';
import { connect } from 'react-redux';
import PostForm from './PostForm';
import { getPosts, deletePost } from '../actions/actions';

class App extends React.Component {

  componentDidMount () {
    this.props.getPosts();
  }

  _getPostId(evt) {
    const postId = evt.target.parentNode.parentNode.getAttribute('data-id');
    this.props.deletePost(postId)
  }

  render() {
    const posts = this.props.postsData.map( (index) => {
      return (
        <tr data-id={index._id}>
          <td> {index.title} </td>
          <td> {index.body} </td>
          <td> <button className="btn btn-primary" onClick={this._getPostId.bind(this)}>Delete</button> </td>
        </tr>
      )
    });

    return (
      <div>
        <nav className="navbar navbar-default navbar-static-top">
          <div className="container">
            <a className="navbar-brand">Blog Admin</a>
          </div>
        </nav>
        <div className="container">
          <PostForm />
          <table className="table">
            <thead>
              <tr>
                <th>Title</th>
                <th>Body</th>
              </tr>
            </thead>
            <tbody>
              {posts}
            </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default connect(state => state, { deletePost, getPosts })(App);

请查看下面我的 reducers.js 文件...

export const postsData =  ( state = [], action ) => {
  switch ( action.type ) {
    case 'GET_POSTS':
      return state;
    case 'STORE_POSTS':
      return [...action.data]
    case 'ADD_POST':
      let newPost = {
        title: action.data.title,
        body: action.data.body
      }
      return state.concat( [newPost] )
    case 'DELETE_POST':
    let postId = action.data;
    return state.filter(p => p._id !== postId)
    default:
      return state;
  }
}

请将下面的 actions.js 文件...

import store from '../store/store.js';

export function getPosts() {
  apiPostCall();
  return { type: 'GET_POSTS' };
}

export function addNewPost(post) {
  apiAddPost(post);
  return { type: 'ADD_POST', data: post }
}

export function deletePost(postId) {
  apiDeletePost(postId);
  return { type: 'DELETE_POST', data: postId }
}

function apiPostCall() {
  $.ajax({
    method: "GET",
    url: "/api/posts",
    dataType: "json"
  }).success(data =>  store.dispatch({ type: 'STORE_POSTS', data }))
}

function apiAddPost(post) {
  $.ajax({
    method: "POST",
    url: "/api/posts",
    data: post,
    dataType: "json"
  }).success()
}

function apiDeletePost(postId) {
  $.ajax({
    method: "DELETE",
    url: "/api/posts/" + postId,
  }).success();
}

我已经解决了这个问题!

所以在注销一些数据后,我发现添加 post 时它不包含数据库中的 id,只有当我重新加载页面时 post s 包含 id 因为它调用 API。

因此,当用户通过表单添加 post 时,我会创建一个 id posted 到 API,然后发送到 Redux 存储.

也感谢您的建议,非常感谢。