如何永久存储使用redux中的axios库发布到API服务器的数据

时间:2017-12-30 07:38:19

标签: reactjs redux axios

我有一个 redux-form ,用于从用户接收数据并将其存储到API.My redux-form如下所示:

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { createPosts } from '../actions/posts_action';

const uuidv1 = require('uuid/v1'); //For generating unique id for each post

class CreatePost extends Component {
  constructor() {
    super();
    this.state = {
      selectValue : ''
  };
  this.handleChange = this.handleChange.bind(this);
  this.renderCategory = this.renderCategory.bind(this);
}

  renderField(field) {
      return(
        <div className="title-design">
            <label className="label-design"> {field.label} </label>
            <input
              type="text"
              className="title-input"
              {...field.input}
            />
            <div className="text-help  has-danger">
              {field.meta.touched ? field.meta.error : ''}
            </div>
      </div>
      );
  }

  handleChange(e) {
    const value=e.target.value;
    this.props.change("categories",value);
    this.setState({selectValue: value}, () => {
      console.log(value)
    });
  }

  renderCategory(field) {
    return(
      <div className="title-design">
        <label className="label-design">{field.label} </label>
          <Field name="category" className="title-input" component="select">
            <option></option>
            <option value="react">React</option>
            <option value="redux">Redux</option>
            <option value="udacity">Udacity</option>
          </Field>

          <div className="text-help has-danger">
            {field.meta.touched ? field.meta.error : ''}
          </div>
      </div>
    );
  }

    onSubmit(values) {

          this.props.createPosts(values, () => {
            uuidv1();
            console.log(uuidv1());
          this.props.history.push('/');
      });
    }



    render() {
      const { handleSubmit } = this.props;

      return (
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <Field
            label="Title for Post"
            name="title"
            component={this.renderField}
          />

          <Field
            label="Post Content"
            name="body"
            component={this.renderField}
          />

          <Field
            label="Category"
            name="category"
            component={this.renderCategory}
            />



          <button type="submit" className="btn btn-primary">Submit</button>
          <Link  to="/">
            <button className="cancel-button">Cancel</button>
          </Link>
        </form>
      );
    }
}

function validate(values) {
  const errors = {} ;

  if (!values.title) {
      errors.title = "Enter a title";
  }

  if (!values.body) {
    errors.body = "Enter some content";
    }

  if(!values.category) {
    errors.category = "Please select a category";
  }

  return errors;
}

export default reduxForm({
  validate : validate,          //validate
  form : 'CreatePostForm'
})(
  connect(null,{ createPosts })(CreatePost)
);
用于创建帖子的

动作创建者

//Action Creator for creating posts
export function createPosts(values, callback) {

  return dispatch => {
    return axios.post(`${API}/posts`,values,{headers})
      .then((data) => {
        callback();
        console.log(data)
      dispatch({
        type: CREATE_POST,
        payload: data
      })
    })
  }
}
帖子的

Reducer 是:

import _ from 'lodash';
import { FETCH_POSTS, FETCH_POST, CREATE_POST } from '../actions/posts_action';

export default function(state = {}, action) {
  switch (action.type) {
    case FETCH_POST:
      return {...state, [action.payload.id]: action.payload};

    case FETCH_POSTS:
     return {posts: { ...state.posts, ...action.payload }};

    case CREATE_POST:
      return {posts: { ...state, ...action.payload}};

     default:
      return state;
  }

}

所以,现在发生的事情是当我尝试将数据发布到服务器时,如果我是console.log,我能够看到数据集,但如果我想向API添加第二组数据,那么第一组数据被删除,只剩下第二组数据。那么,如何将每组数据的记录保存到API?

修改1:

我的index.js文件包含所有reducer:

import { combineReducers } from 'redux';
import PostReducer from './PostsReducer';
import { reducer as formReducer} from 'redux-form';
import CategoriesReducer from './CategoriesReducer';

const rootReducer = combineReducers({
    posts: PostReducer,
    categories: CategoriesReducer,
    form : formReducer
});

export default rootReducer;

编辑2:我更新的减速器:

import _ from 'lodash';
import { FETCH_POSTS, FETCH_POST, CREATE_POST } from '../actions/posts_action';

export default function(state = {posts: [] }, action) {
  switch (action.type) {
    case FETCH_POST:
      return {...state, [action.payload.id]: action.payload};

    case FETCH_POSTS:
     return {posts: { ...state.posts, ...action.payload }};

    case CREATE_POST:
      return {...state, posts: [...posts, ...action.payload]};

     default:
      return state;
  }

}

编辑3:“数据”内容的屏幕截图

post_data

1 个答案:

答案 0 :(得分:0)

首先将您的posts默认值设置为默认状态,以便稍后我们可以使用数组上的spread运算符来生成突变。

export default function(state = { posts: [] }, action) {
  ...
}

然后,目前您正在使用有效负载替换redux存储的帖子切片:

case CREATE_POST:
  {posts: { ...state, ...action.payload}};

您的商店会发生以下情况:

{
  posts: {
    posts: action.payload
  },
  categories,
  form
}

您应该只添加新帖子:

case CREATE_POST:
  {...state, posts: [...state.posts, action.payload]};

您的商店会发生以下情况:

{
  posts: {
    posts: [post1, post2, ... , action.payload]
  },
  categories,
  form
}