在redux中将业务逻辑放在哪里?行动或存储 [英] Where to put business logic in redux? action or store

查看:360
本文介绍了在redux中将业务逻辑放在哪里?行动或存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自回流 Redux .在Reflux中,您的业务逻辑仅存在于商店中,但在 Redux 中似乎有所不同.例如,在" Redux "中,我有异步操作" ,我用" redux-thunk "来实现它.

i come from Reflux to Redux. in Reflux your business logic is exist only in store but in Redux its seems different..for example in "Redux" i have "async-action" and i implemented it with "redux-thunk" .

在一种情况下,我想检查我的动作,如果需要,我向服务器发送请求并获取一些数据.在这种情况下,我必须检查我的操作逻辑,而实际上我的业务逻辑存在于操作中并存储在一起,这不好..您的解决方案是什么?

in one scenario i want to check something in my action and if that needed i send request to server and get some data. i this case i have to check my logic in my action and actually my business logic is exist in action and store together and its not good.. what is your solution?

例如,我有一个复选框,我检查了一些条件,如果结果为真,我向服务器发送一个请求,这是我的动作代码,如您所见,我的业务逻辑在我的动作和我的Reducer上:

for example i have checkbox and i check some condition and if the result is true i send a request to server here is my action code and as you see my business logic is on my Action and my Reducer:

export function onCheckboxClick({itemId}) {
  return (dispatch, getState) => {
      let state = getState().get('myReducer');

      let myConditionResult = state.get('foods').get(0).get('test');//for exmaple check some condition in my store

      dispatch({type: 'CHECKBOX_CLICK', itemId});// for change the checkbox checked

      if (myConditionResult) {
        myApi.deleteOrderItem({itemId}).then(()=> {
          dispatch({type: 'DELETE_ORDER_ITEM_FULFILLED', itemId});
        }).catch((err)=> {
          console.log(err);
          dispatch({type: 'DELETE_ORDER_ITEM_REJECTED', itemId});
        });
      }
   };
}

预先感谢

推荐答案

如上所述,根据您的用例,有多种方法可以执行此操作.我能做的是列出您从推测用例来看更合适的东西.

As mentioned, there are multiple ways to perform this action depending on your use case. What I can do is list you what seems more appropriate from speculating your use case.

1.组件内部的逻辑.

可以使用您还可以将动作导入到此组件文件中,并将动作也映射到道具.

You also import the action into this component file and map the action to props as well.

下面的示例演示如何将状态和操作引入到Component文件中.如何使用它取决于您.我把它放在一个简单的上下文中.因此,您可以在希望执行逻辑的点调用myFunction().

The example below demonstrates how you bring the state and action into the Component file. How you use it is up to you. I've put it into a simple context. So you may invoke myFunction() at the point you wish perform the logic.

MyComponent.js

import React, { Component} from 'react'
import { connect } from 'react-redux'
import { onCheckboxClick } from 'path/to/action'

class MyComponent extends Component {

    myFunction() {
         const { theConditiion, onCheckboxClick } = this.props

         if (theConditiion) {
             onCheckboxClick({itemId: 'someItemid'})
         }
    }

    render() {
      //...
    }
 }


const mapStateToProps = (state) => ({
    theCondition: state.wherever.the.data.lives.in.store
})

export default connect(
    mapStateToProps,
    { onCheckboxClick }
    )(MyComponent)

因此,对于上面的示例,您可以删除onCheckboxClick函数中当前具有的条件检查.

Therefore, you can remove the conditional checks you currently have within your onCheckboxClick function for the example above.

2.将逻辑放入中间件中.

下面的示例演示了如何调度动作,但是首先,捕获"特定类型的动作,前提是条件为true,则可以进行api调用并调度进一步的动作(如果为false),将操作传递给下一个中间件.

The example below demonstrates how you can dispatch action(s) but first, 'catching' a particular type of action, given that that a condition is true, you can make an api call and dispatch further actions, if false, just pass the action to the next middleware.

myMiddleware.js

const onCheckboxClick = store => next => action => {
    if (action.type == 'CHECKBOX_CLICK') {

    let theConditiion = store.getState().wherever.the.data.lives.in.store

    if (theConditiion) {
        // 1. make the api call here, or,
        // 2. dispatch an action specific to handling api calls.
        // E.g. Create another middleware to catch action type `API_CALL` 
        // This middleware can then handle all api calls, and dispatch actions for api requests, responses and errors. 

        const newAction = {...action, type: 'API_CALL' }
        store.dispatch(newAction)

        // When you use store.dispatch(), the action will be passed back to the top of the middleware chain. 
    }

    return next(action) // this will pass the action to the next middleware in the chain.

}

export default onCheckboxClick

这是一个广泛的概述,可帮助您思考最有效的方法.请记住,随着应用程序的开发,您会注意到可以在其自身功能中使用重复的逻辑.

This is a broad overview to help you get thinking what works best. Keep in mind, as your app develops, you will notice where repeated logic can be made into its own functions.

这篇关于在redux中将业务逻辑放在哪里?行动或存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆