简体   繁体   English

从一个动作文件中分派来自另一个reducer文件的动作是一种反模式吗?

[英]Is it an anti pattern to dispatch actions from an action file that are subscribed to from a different reducer file?

Usually in my Redux projects I have action and reducer files that come in pairs. 通常,在我的Redux项目中,我有两个成对的action和reducer文件。 So in my actions folder I will have a posts.js and in my reducers folder I will also have a posts.js . 因此,在我的actions文件夹中,我将有一个posts.js ,在我的reducers文件夹中,我还将有一个posts.js The posts action file usually just dispatch action types that are subscribed to in the posts reducer file. post操作文件通常只是调度post reducer文件中预订的操作类型。

But now I need to dispatch an action type from the posts action file that is subscribed to from the authors reducer file. 但是,现在我需要从posts动作文件中调度一个动作类型,该动作类型是从authors reducer文件中订阅的。 Is this okay or considered an anti-pattern? 这样行之有效还是被视为反模式?

That isn't anti-pattern at all. 那根本不是反模式。 It's good code-reusability and especially useful for error-handling. 它具有良好的代码可重用性,并且对于错误处理特别有用。

Consider the following example: 考虑以下示例:

posts.js posts.js

import { GET_POSTS } from "./actions/types"
import { setErrors } from "./actions/errors"
import axios from "axios"

export const getPosts = () => {
   return (dispatch) => {
       axios.get("/api/posts")
            .then((res) => {
                dispatch({
                   type: GET_POSTS,
                   payload: res.data
                })
            })
            .catch((errors) => {
                dispatch(setErrors(errors.response.data))
            }
   }
}

errors.js errors.js

const setErrors = (errors) => {
   return {
      type: SET_ERRORS,
      payload: errors
   }
}

So instead of defining a completely new post-related errors action inside posts.js , it makes sense to just import an existing one that is subscribed to your errors-reducer (if any). 因此,与其在posts.js中定义一个全新的与帖子相关的错误操作, 不如仅仅导入一个已订阅您的减少错误工具(如果有)的现有操作。 The same could be said about using your author and post actions together. 关于使用您的作者和一起发布操作,也可以这样说。

It depends on which design pattern you are following. 这取决于您遵循的设计模式。 As you may have all your actions in a single file. 因为您可能将所有操作都放在一个文件中。 For your case you can export the action creator from one file and just import it where you want same action creator. 对于您的情况,您可以从一个文件导出动作创建者,然后将其导入到您想要相同动作创建者的位置。 This way you can have the same syncing between action creators and reducers as you are talking about. 这样,您就可以在动作创建者和减速器之间进行相同的同步。

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

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