React Redux - 在 Reducer 中添加异步方法是一种反模式吗? [英] React Redux - Is adding async method in a Reducer an anti pattern?

查看:84
本文介绍了React Redux - 在 Reducer 中添加异步方法是一种反模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对整个 react-native/redux 世界还很陌生,所以也许这个问题听起来很愚蠢:)

I'm pretty new to the whole react-native / redux world, so maybe this question will sound dumb :)

我知道对于 API 调用或类似的东西,约定是使用中间件,但它总是必要的吗?(它添加了很多样板文件).

I know that for an API call, or stuff like that, the convention is to use middleware, but is it always necessary? (It adds a lot of boilerplate).

我成功地在 reducer 中添加了一个异步方法来管理设备 API 连接,例如应用内或本地通知,但我想知道以这种方式处理它是否可以.

I succefully added an async method in a reducer to manage a device API connection, such as In-App or Local Notifications, but I wonder if it is ok to handle it this way.

例如,在我的减速器中有这个方法:

For instance, in my reducer there is this method:

function initInApp(state, itemSkus){
  init(state, itemSkus);
  return {
    ...state,
    itemSkus: itemSkus,
  }
}

还有这个,它管理异步部分:

And this one, which manage the async part:

async function init(state, itemSkus){
  try {
    if( !state.isInit ){
      const prepare = await Promise.all(RNIap.prepareAndroid());
      return{
        ...state,
        isInit: true,
        errorCode: false,
      }
    }
    else {
       return ...state;
    }
  } catch (errorCode) {
    return{
      ...state,
      isInit: false,
      errorCode: errorCode,
      itemSkus: itemSkus
    }
  }
}

也许它在性能方面效率不高或难以维护..您对此有何看法?

Maybe it's not efficient in terms of performances or hard to maintain..What are your thoughts on this?

谢谢:)

推荐答案

是的.Reducers 不应该有任何副作用.Reducers 需要是 Pure Functions 才能让 redux 高效工作.这里有几个链接试图解释 为什么使用 redux需要 reducer 是纯函数为什么纯 reducer 如此在 redux 中很重要.

Yes. Reducers should not have any side effects. Reducers need to be Pure Functions for redux to work efficiently. Here are a couple links that attempt to explain why redux needs reducers to be pure functions and why are pure reducers so important in redux.

正如其他人指出的那样,thunk 中间件是在 React 中处理异步的常用方法.

As others indicated thunk middleware is a common way to handle asynch in react.

另一种不需要任何库的方法是通过称为Fat Action Creators"的模式.动作创建者可以处理异步操作.他们这样做的方法是返回一个围绕函数的调度"包装器,因此它可以自己调度操作.

Another method, that does not require any library is through a pattern known as "Fat Action Creators". Action creators can handle asynch operations. The way they do this is by returning a "dispatch" wrapper around the function, so it can itself dispatch actions.

以下是摘自媒体文章的示例:
在哪里我将我的业务逻辑放在 React-Redux 应用程序中
(本文也链接到 redux 常见问题):

Here is an example of this taken from the Medium Article:
Where Do I Put my Business Logic In a React-Redux Application
(This article is also linked to from the redux FAQ):

const fetchUser = (dispatch, id) => {
  dispatch({ type: USER_FETCH, payload: id });
  axios.get(`https://server/user/${id}`)
   .then(resp => resp.data)
   .then(user => dispatch({ type: USER_FETCH_SUCCESS, 
                            payload: user }))
   .catch(err => {
     console.error(err); // log since might be a render err
     dispatch({ type: USER_FETCH_FAILED, 
                            payload: err, 
                            error: true });
   });
};

redux-thunk 以外的软件包包括:

Packages other than redux-thunk include:

所有业务逻辑和操作副作用的一个地方"使用 redux-logic,你可以自由地在你的最喜欢的JS风格:`

"One place for all your business logic and action side effects" "With redux-logic, you have the freedom to write your logic in your favorite JS style:`

  • 普通回调代码 - dispatch(resultAction)
  • 承诺 - 返回 axios.get(url).then(...)
  • async/await - result = await fetch(url)
  • observables - ob$.next(action1)`

  • redux-saga

    redux-saga 是一个库,旨在使应用程序的副作用(即异步事物,如数据获取和不纯的事物,如访问浏览器缓存)更易于管理、更高效地执行、更易于测试以及更好地处理故障.使用生成器,因此请确保您使用它们感到舒适.

    redux-saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, simple to test, and better at handling failures. uses generators so make sure you're confortable using them.

  • redux-observable,如果你喜欢 RxJS Observables
    这个库是由 Jay Phelps 创建的,这个 medium post "redux-observable" 是本·莱什 (Ben Lesh) 所著.两者都在 React 社区中广为人知.

  • redux-observable, if you prefer RxJS Observables
    This library was created by Jay Phelps, and this medium post "redux-observable" was written by Ben Lesh. Both well known in the react community.

    redux-thunk 为了完整性.

    其他包在前面提到的文章中列出:
    在哪里做我将我的业务逻辑放在 React-Redux 应用程序中

    Additional packages are listed in the article mentioned earlier:
    Where Do I Put my Business Logic In a React-Redux Application

    一切顺利!

    这篇关于React Redux - 在 Reducer 中添加异步方法是一种反模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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