减速器-更新完整状态

时间:2020-10-11 04:15:35

标签: javascript reactjs react-hooks use-reducer

我想在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();
      }
    };

1 个答案:

答案 0 :(得分:2)

可能应该是:

      case "SET_INIT_DATA":
          return action.payload;

您无法使用,因为这是语法错误。 JS对象初始化需要键,值对(或object property short form)或散布运算符。您未提供任何内容,因此是语法错误。

由于action.payload是一个合适的对象,因此它有资格从化简器中返回,并且无需创建包装对象,因为您想要的是它。

相关问题