2

我正在使用带有 react-redux 和 redux-actions 的 React。

我有以下不断告诉我的减速器

意外的标记,预期的“,”

但我不知道为什么。

comments.js (reducer):

import { handleActions } from "redux-actions";
import {
  GET_COMMENTS,
  SET_COMMENTS,
  ADD_COMMENT
} from "../constants/actionTypes";

export default handleActions(
  {
    [GET_COMMENTS]: (state, action) => state,
    [ADD_COMMENT]: (state, action) => {
      const comments = {
        ...state.comments,
        action.payload
      };
      return {
        ...state,
        comments
      };
    },
    [SET_COMMENTS]: (state, action) =>
      Boolean(action.payload) ? action.payload : state
  },
  {}
);

引起麻烦的动作是ADD_COMMENT。我已经尝试了以下方法:

[ADD_COMMENT]: (state, action) => {
  ...state,
  comments: {
    ...state,
    action.payload
  }
}

或者

[ADD_COMMENT]: (state, action) => ({
      ...state,
      comments: {
        ...state,
        action.payload
      }
})

也:

[ADD_COMMENT]: (state, action) => {
  return {
      ...state,
      comments: {
        ...state,
        action.payload
      }
  }
}

我不明白为什么我的代码不正确,我在 atom 中的 linter 说它是 action 和 payload 之间的点,但我不确定。

动作创建者只返回一种 ADD_COMMENT 类型和单个评论的有效负载,格式如下:

{
    "id": 3,
    "parent": 1,
    "author": "admin",
    "author_is_staff": true,
    "content": "This is a test comment using the API rather than the Admin page, with author specified, with view changed"
}
4

1 回答 1

6

您正在尝试在没有键的对象中包含变量:

// This is fine
const comments = {
  ...state.comments
}

// This is not
const comments = {
  actions.payload
}

// Possible alternative:
const comments = {
  ...state.comments,
  payload: actions.payload
}

// Or if you want to destructure `actions.payload`:
const comments = {
  ...state.comments,
  ...actions.payload
}
于 2018-10-01T23:07:43.067 回答