【问题标题】:React Redux Unexpected token, expected ","React Redux 意外的令牌,预期的“,”
【发布时间】:2019-03-07 02:06:17
【问题描述】:

我正在使用带有 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"
}

【问题讨论】:

    标签: reactjs redux react-redux redux-actions


    【解决方案1】:

    你试图在没有键的对象中包含一个变量:

    // 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
    }
    

    【讨论】:

    • 啊。我现在在上课,但当我出去的时候我会试试看。我绝对认为你是对的,现在我听到了,这很有道理。 state.cmets 是对象的对象,所以我相信我必须将 actions.payload 解构到 cmets 中。将验证并回复您。
    • 你是对的。我能够通过首先规范化数据然后将 actions.payload 解构到新的 cmets 状态来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2018-09-13
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多