用状态

时间:2019-02-26 14:06:39

标签: javascript reactjs redux react-redux

在安装组件时,我从API获取信息,当成功时,状态如下:

    {
        "brief":"No brief given",
        "tasks":[
            {
                "_id":"5c74ffc257a059094cf8f3c2",
                "task":"87 Development Task 7",
                "project":"5c7458abd2fa91567f4e4f03",
                "date_created":"2019-02-26T08:58:42.260Z",
                "__v":0
            }
        ],
        "_id":"5c7458abd2fa91567f4e4f03",
        "owner":{
            "_id":"5c5af553eea087426cd5f9b9",
            "name":"Test test",
            "email":"test@test.com",
            "avatar":"placeholder.jpg",
            "created_at":"2019-02-06T14:55:15.321Z",
            "__v":0
        },
        "name":"87 Development Project 1",
        "status":"Pending",
        "slug":"87-development-project-1",
        "created_at":"2019-02-25T21:05:47.643Z",
        "__v":0
   }

我想将一个任务标记为已完成,但是我对我的化简和动作感到困惑,流程是用户单击一个带有触发动作的按钮,该动作发布到我的api,该api用更新的任务对象进行响应。但是,我对于如何将更新后的任务对象移入我的状态感到困惑,因为该对象位于状态内的数组中?有人可以帮我吗?

这是我的动作

import axios from "axios";

import { COMPLETE_TASK } from "./types";

// Set logged in user
export const completeTask = id => dispatch => {
  axios.post(`/api/tasks/complete`, { id }).then(res => {
    dispatch({
      type: COMPLETE_TASK,
      payload: res.data
    });
  });
};

这是我的减速器,

import { COMPLETE_TASK } from "../actions/types";

const initialState = { project: { tasks: [], owner: {} } };

export default function(state = initialState, action) {
  switch (action.type) {
    case COMPLETE_TASK:
      return {
        ...state,
        ????
      };
    default:
      return state;
  }
}

现在我的感觉是我的初始状态会清除以前的任何状态?其次,如何将返回的有效负载移到正确的任务对象中?

1 个答案:

答案 0 :(得分:0)

您的API /api/tasks/complete的响应是什么样的?您的API是否应该完成任务或检索任务列表?

无论如何,通常在减速器中使用Array.prototype.mapArray.prototype.filterArray.prototype.reduce,例如如果您的API用于将任务标记为已完成并返回已正确标记为已完成的任务的ID,那么化简器可能看起来像这样:

export default function(state = initialState, action) {
  switch (action.type) {
    case COMPLETE_TASK:
      return {
        ...state,
        tasks: state.tasks.filter((task) => {
          return task.id !== action.taskToCompleteId
        })
      };
    default:
      return state;
  }
}