【问题标题】:reducer - update the complete statereducer - 更新完整状态
【发布时间】:2020-10-11 04:15:35
【问题描述】:

我想向 reducer 添加一个案例,我想在其中设置完整状态,而不是任何特定属性。

更新特定属性[SET_SELECTED_PAGE,UPDATE_MESSAGE_DISPLAYED] 工作正常。但是当我尝试SET_INIT_DATA 时,我得到错误Parsing error: Unexpected token, expected ","SET_INIT_DATA 的有效负载将具有完整的 json。

我的状态会是这样的

{
  "user": "",
  "selectedPage": "home",
  "message": "Message from admin",
  ...
}

代码:

 const reducer = (state, action) => {
      switch (action.type) {
        case "SET_SELECTED_PAGE":
          return {
             ...state,
            selectedPage: action.payload 
          };
        case "UPDATE_MESSAGE_DISPLAYED":
          return {
              ...state,
              messageDisplayed: action.payload 
            };
      case "SET_INIT_DATA":
          return {
              action.payload // getting error Parsing error: Unexpected token, expected ","
           }; 
        default:
          throw new Error();
      }
    };

【问题讨论】:

    标签: javascript reactjs react-hooks use-reducer


    【解决方案1】:

    应该是这样的:

          case "SET_INIT_DATA":
              return action.payload;
    

    你的没有用,因为它是一个语法错误。 JS 对象初始化需要键、值对(或object property short form)或扩展运算符。你没有提供所以这是一个语法错误。

    由于action.payload 是一个合适的对象,它可以很好地从reducer 返回,无需创建包装器对象,因为您希望对象保持原样。

    【讨论】:

    • 谢谢。您能否提供解释,为什么它应该是这样而我的不起作用
    • 为你添加了解释。
    猜你喜欢
    • 2019-07-28
    • 2023-01-28
    • 2018-08-04
    • 1970-01-01
    • 2018-03-12
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多