简体   繁体   English

使用Redux防止重复的最佳做法是什么?

[英]What are the best practices for preventing duplicates with Redux?

如果你正在使用Redux,并且你有一个处于状态的数组,但你想防止重复的项目进入该数组,你应该防止重复项添加到reducer中的数组中, 还是应该这样做在动作创作者?

Generally, Redux action creators should avoid knowing anything about the application state, as the author of Redux, Dan Abramov, describes : 通常,Redux动作创建者应该避免了解应用程序状态, 正如Redux的作者Dan Abramov所描述的那样

In general accessing state in action creators is an anti-pattern and you should avoid this when possible. 一般来说,在操作中访问状态创建者是一种反模式,你应该尽可能避免这种情况。

The best practices for Redux dictate that action creators just create an action to represent that something happened, without considering how that will affect the state. Redux的最佳实践要求动作创建者只是创建一个动作来表示发生的事情,而不考虑它将如何影响状态。 In other words, an action means 'something happened', not 'the state needs to be changed'; 换句话说,一个动作意味着“发生了什么事”,而不是“状态需要改变”; it's fine to completely ignore an action if it's not relevant. 如果不相关,可以完全忽略某个动作。

On the other hand, a reducer is specifically intended to be a pure function of the previous state and the action, so it is perfectly placed to judge whether an action requires state mutation. 另一方面,减速器具体地意图是先前状态和动作的纯函数,因此完全可以判断动作是否需要状态变异。

So, in summary, the reducer is probably the best choice, so your action creators can remain 'thin'. 因此,总之,减速器可能是最佳选择,因此您的动作创建者可以保持“瘦”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM