现在有很多人在谈论redux城的最新成员,redux-saga/redux-saga。它使用生成器函数来监听/分派动作。

在我把我的脑袋绕在它周围之前,我想知道使用redux-saga的优点/缺点,而不是下面的方法,我使用redux-thunk与async/await。

组件可能是这样的,像往常一样分派动作。

import { login } from 'redux/auth';

class LoginForm extends Component {

  onClick(e) {
    e.preventDefault();
    const { user, pass } = this.refs;
    this.props.dispatch(login(user.value, pass.value));
  }

  render() {
    return (<div>
        <input type="text" ref="user" />
        <input type="password" ref="pass" />
        <button onClick={::this.onClick}>Sign In</button>
    </div>);
  } 
}

export default connect((state) => ({}))(LoginForm);

然后我的动作看起来像这样:

// auth.js

import request from 'axios';
import { loadUserData } from './user';

// define constants
// define initial state
// export default reducer

export const login = (user, pass) => async (dispatch) => {
    try {
        dispatch({ type: LOGIN_REQUEST });
        let { data } = await request.post('/login', { user, pass });
        await dispatch(loadUserData(data.uid));
        dispatch({ type: LOGIN_SUCCESS, data });
    } catch(error) {
        dispatch({ type: LOGIN_ERROR, error });
    }
}

// more actions...

// user.js

import request from 'axios';

// define constants
// define initial state
// export default reducer

export const loadUserData = (uid) => async (dispatch) => {
    try {
        dispatch({ type: USERDATA_REQUEST });
        let { data } = await request.get(`/users/${uid}`);
        dispatch({ type: USERDATA_SUCCESS, data });
    } catch(error) {
        dispatch({ type: USERDATA_ERROR, error });
    }
}

// more actions...

当前回答

除了图书馆作者相当彻底的回答之外,我将添加我在生产系统中使用saga的经验。

优点(使用saga):

Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test. redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point. Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.

Con:

发电机的语法。 有很多概念要学。 API的稳定性。redux-saga似乎还在添加新功能(比如Channels?),社区也没有那么大。如果库有一天进行了不向后兼容的更新,就会有问题。

其他回答

2020年7月更新:

在过去的16个月里,React社区最显著的变化可能是React钩子。

根据我的观察,为了获得与功能组件和钩子更好的兼容性,项目(即使是那些大型项目)倾向于使用:

Hook + async thunk (Hook使一切都非常灵活,所以你可以将async thunk放在你想要的地方,并将其作为普通函数使用,例如,仍然在操作中编写thunk。ts然后使用dispatch()来触发坦克:https://stackoverflow.com/a/59991104/5256695), useRequest, GraphQL/Apollo useQuery useMutation react-fetching-library 其他流行的数据获取/API调用库、工具、设计模式等

相比之下,redux-saga在大多数API调用的正常情况下并没有比上面的方法提供显著的好处,同时通过引入许多saga文件/生成器增加了项目的复杂性(也是因为redux-saga的最后一个版本v1.1.1是在2019年9月18日,这是很久以前的事了)。

但是redux-saga仍然提供了一些独特的功能,如赛车效果和并行请求。因此,如果您需要这些特殊功能,redux-saga仍然是一个不错的选择。


2019年3月原帖:

这是一些个人经历:

For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk. One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk. In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions. Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail. Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.

In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.

无论如何,redux-saga并不比redux本身更困难和复杂,而且它没有所谓的陡峭的学习曲线,因为它的核心概念和api非常有限。花少量的时间学习redux-saga可能在未来的某一天对你有益。

在我回顾了一些不同的大型React/Redux项目的经验后,Sagas为开发人员提供了一种更结构化的代码编写方式,更容易测试,也更不易出错。

是的,刚开始这有点奇怪,但大多数开发者在一天之内就足够理解它了。我总是告诉人们不要担心yield一开始会做什么,一旦你写了几个测试,它就会来找你。

我曾经见过一些项目,在这些项目中,坦克被当作MVC模式的控制器来处理,这很快就变成了一个不可维护的混乱。

我的建议是,当你需要A触发B类型的与单个事件相关的东西时使用saga。对于任何可能跨越许多操作的东西,我发现编写自定义中间件并使用FSA操作的元属性来触发它更简单。

为了给这个答案一些上下文:嗨,我是Redux维护者。

我们最近在Redux文档中添加了一个新的Side Effects methods页面,它将提供关于所有这些内容的许多信息,但我将尝试在这里写一些简短的内容,因为这个问题得到了大量的曝光。

在2022年,我们将监听器中间件添加到官方Redux工具包中,用于“响应式Redux逻辑”。它可以做sagas可以做的大部分事情(例外是通道),而不需要生成器语法和更好的TypeScript支持。 但这并不意味着你应该用侦听器中间件来编写所有的东西——我们建议在可能的情况下总是先使用thks,在thks不能做你想做的事情时再使用侦听器中间件。

一般来说,我们在2023年的立场是,只有当你有其他中间件无法满足的特定需求时,你才应该使用saga。(本质上:如果你需要频道。)

我们的建议是:

数据抓取

使用RTK Query作为数据获取和缓存的默认方法 如果RTKQ不完全适合,使用createAsyncThunk 只有在其他方法都没用的情况下,才会求助于手写的感谢信 不要使用saga或可观察对象来获取数据!

对动作/状态变化做出反应,异步工作流

使用RTK监听器作为默认响应存储更新和编写长时间运行的异步工作流 只有当监听器不能很好地解决你的用例时,才使用saga / observable

带有状态访问的逻辑

对于复杂的同步和适度的异步逻辑,包括对getState的访问和调度多个操作,可以使用坦克

我只是想从我的个人经验(使用sagas和thunk)中补充一些评论:

传奇故事很适合测试:

您不需要模拟用效果包装的函数 因此,测试是干净的,可读的,易于编写的 在使用saga时,动作创建者通常会返回简单的对象字面量。与thunk的承诺不同,它也更容易测试和断言。

传说更有力量。你在一个坦克动作创造者中可以做到的所有事情,你也可以在一个传奇中做到,但反之亦然(至少不容易)。例如:

等待一个/多个动作被分派(采取) 取消现有的例程(取消,taklatest, race) 多个例程可以监听相同的动作(take, takeEvery,…)

Sagas还提供了其他有用的功能,它概括了一些常见的应用程序模式:

监听外部事件源的通道(例如websockets) Fork模型(Fork, spawn) 节气门 ...

Sagas are great and powerful tool. However with the power comes responsibility. When your application grows you can get easily lost by figuring out who is waiting for the action to be dispatched, or what everything happens when some action is being dispatched. On the other hand thunk is simpler and easier to reason about. Choosing one or another depends on many aspects like type and size of the project, what types of side effect your project must handle or dev team preference. In any case just keep your application simple and predictable.

一个小提示。生成器是可取消的,async/await - not。 举个例子,选什么并没有什么意义。 但对于更复杂的流,有时没有比使用生成器更好的解决方案了。

所以,另一个想法可能是使用带有还原坦克的发电机,但对我来说,这就像试图发明一辆有方轮子的自行车。

当然,生成器更容易测试。