为啥 redux action 需要能够 serializable?

2022-09-27 21:43:29 +08:00
 jchnxu

https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants

While it is certainly possible to manually create action objects everywhere, and write each type value by hand, defining reusable constants makes maintaining code easier.

我是真的不觉得 easy ,95% 的 action 都是用那么一两次。有没有同学遇到过 action 这个抽象真的有用的?

---- 背景 ----

写 redux action 写的很烦。zustand 这种更简单的,也需要 action 。所以干脆传了一个统一的匿名函数,利用 closure 直接拿了很多变量。但就报了这个 warning

reducer: (state, action) => {
    if (!state) {
      throw new Error("root state should not be empty");
    }

    let newState = { ...state };
    if (action.type === "func") {
      newState = produce(state, action.func); // import produce from 'immer'  
    }

    return newState;
  },
1598 次点击
所在节点    React
10 条回复
sweetcola
2022-09-27 22:09:53 +08:00
As with state, serializable actions enable several of Redux's defining features, such as time travel debugging, and recording and replaying actions.
标题下面第一句就回答了

https://react-redux.js.org/tutorials/quick-start#how-to-read-this-tutorial
> For this tutorial, we assume that you're using Redux Toolkit and React Redux together, as that is the standard Redux usage pattern.

RTK(Redux Toolkit) 已经是目前的 Redux 的标准写法了,该抛弃以前的这种旧写法了。
jchnxu
2022-09-27 22:30:22 +08:00
RTK 也要创建 action 啊,只是没有字符串而已。或者我应该这么问,time travel 其实 直接用 state diff 就能做了,抽象一层 action 的好处是?

主要是我 95% 的 action 就是 SET_LOADING, SET_XXX 。 很想直接写 state.isLoading = ...

即便是复杂一点的,一个 normalized 后的 state ,也能直接写。

```
getUsers => state.topUserIds.map(u => state.userStore[u.id]);

```

找到一篇作者的回答,但这并不能太说服我。https://github.com/reduxjs/redux/issues/628#issuecomment-137547668
ospider
2022-09-27 23:15:55 +08:00
精力还是别放在 redux 这种过时的东西上了……
Dotennin
2022-09-28 00:11:43 +08:00
确实烦, 一般会通用的 action, 作为 state 接口互动
yyfearth
2022-09-28 04:40:53 +08:00
@jchnxu 这个 state 不是 observable 或者 proxy 啥的
所以你不能直接 state.isLoading = 因为没有代码能够知道你做了这个修改 然后去触发
必须通过一个方法来处理并且去触发

如果你喜欢 state.isLoading=这样 你要换别的 state manager
不少新的 lib 都是用 observable 或者 proxy 或者生产代码的方法支持 你喜欢的这种方法
Jzdoxc
2022-09-28 09:20:07 +08:00
@ospider 现在最常用的是什么呢,可否给个关键词
ericgui
2022-09-28 09:26:34 +08:00
@ospider .....

你确定吗?
mxT52CRuqR6o5
2022-09-28 09:52:59 +08:00
我这么说吧,redux 的那些都是针对 redux devtools 设计的,虽然写起来很麻烦,但是 devtools 真的很好用
像 mobx 写起来很爽,但 devtools 用起来真的一言难尽
jchnxu
2022-09-28 13:45:20 +08:00
@yyfearth #5 state.isLoading 只是打一个比方,意思是能不能不用抽象 action ,直接改 state 。或者说等到必要的时候再抽象 action
jchnxu
10 天前
兄弟们 zustand 挺好的。我的问题就是 98% 的时候用不上一个 sub pub ,只是简单的 get set

另外满足我的一个需求是,在 react 之外调用也挺方便的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/883373

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX