状态不使用Redux进行更新

时间:2016-06-18 12:43:08

标签: javascript reactjs ecmascript-6 redux react-redux

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

请在此处查看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();
}

1 个答案:

答案 0 :(得分:1)

我设法解决了这个问题!

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

因此,当用户通过表单添加帖子时,我会创建一个id,该帖子会发布到API,然后发送到Redux商店。

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