如何获取axios.get数据以及将其放置在redux reducer初始状态的位置

时间:2019-10-15 11:34:47

标签: reactjs redux axios json-server

我正试图从json获取array json-server @port 3001数据,我希望将此数据以array的形式置于我的reducer的初始状态。基本上,它是redux的CRUD应用。我认为我使用的语法不正确。

这是json数据库中的后端数据。

{
    "posts": [
        {
            "id": "2019-10-14T07:47:34.044Z",
            "title": "Shani",
            "message": "KHRP",
            "edititng": false
        },
        {
            "id": "2019-10-14T07:50:03.954Z",
            "title": "Shani",
            "message": "KHRPUR",
            "edititng": false
        },
        {
            "id": "2019-10-14T16:19:55.551Z",
            "title": "Sherry",
            "message": "BWP",
            "edititng": false
        }
    ]
}
const postReducer = (state = [], action) => {
    switch (action.type) {
        case 'ADD_POST':
            return state.concat([action.data]);
        case 'DELETE_POST':
            return state.filter((post) => post.id !== action.id);
        case 'EDIT_POST':
            return state.map((post) => post.id === action.id ? {
                ...post,
                editing: !post.editing
            } : post);
// I can add post with just.
axios.post('/posts', data) 
// in my ADD_POST action.

但是,当我尝试使用axios.get('/posts', params)和许多其他方法将我所有的帖子都发布到AllPost页面上时,我尝试了但我无法获取数据。 我想问的另一件事是,我应该获取json数据并将其传递来直接存储吗?如果是,那么如何..

1 个答案:

答案 0 :(得分:1)

types.js

export const ADD_POST= 'ADD_POST';

action.js

import * as types from './types';

const setDocumentData = data => ({
  type: types.ADD_POST,
  data,
});

export const setData = details => dispatch => {
  dispatch(setDocumentData(details));
};

reducer.js

import * as types from 'store/actions/types';

const initialState = {
  application: {},
};

const Application = (state = initialState, action) => {
  switch (action.type) {
    case types.ADD_POST:
      let setOldData = {...state.application};
      setOldData = action.details;

      return {
        ...state,
        application: setOldData,
      };

    default:
      return state;
  }
};