【问题标题】:Processing return of async call in react-redux在 react-redux 中处理异步调用的返回
【发布时间】:2016-10-14 06:33:13
【问题描述】:

假设有一个返回一些数据的async read(args) 方法。 我使用redux-thunkredux-promise 来调度异步操作。 该方法需要访问 redux 存储才能读取状态树的某些部分,以及传递给 thunkMiddleware.withExtraArguments() 的额外参数。该方法是一种抽象,该方法的具体实现可能需要访问状态树的不同部分(例如,当前会话的 ID、数据源的名称等)。 从方法返回的数据需要经过后处理,然后才能传递给执行渲染的组件。

我正在考虑以下方法来实现上述内容:

方法1.getState函数传递给async read()方法;像这样实现动作创建器:

  const actionRead=()=>async (dispatch, getState, {rpc})=>{
   dispatch({type:ActionReadStarted, ...});
   let data=await read(rpc, getState);
   // post process the data as needed
   dispatch({type:ActionReadComplete, data});
  };

我不喜欢这里的是直接传递给read 方法的getState

方法 2. 使 read() 方法本身成为动作创建者:

const actionRead=()=>async (dispatch, getState, {rpc})=>{
 dispatch({type:ActionReadStarted, ...});
 let data=await dispatch(read());
 // post process the data as needed
 dispatch({type:ActionReadComplete, data});
};

const read=()=>(dispatch, getState, {rpc})=>{
 const arguments=getState().some_arguments;
 return rpc.actual_read_returns_promise(arguments);
}

在这两种情况下,reducer 只是将数据写入存储。我不能把后处理逻辑放在reducer中,因为它可能会产生副作用。

我个人赞成第二种方法,但这篇文章建议dispatch 不应返回任何数据:https://github.com/reactjs/redux/issues/61

我对大师的问题:哪种方法更符合react-redux 最佳实践?有没有更好的方法来实现上述?

编辑: 现在我正在使用修改后的第一种方法:

const actionRead=(args)=>async (dispatch, getState, api)=>{
 dispatch({type:ActionReadStarted, ...});
 let data=await read(args)(dispatch, getState, api);
 // post process the data as needed
 dispatch({type:ActionReadComplete, data});
};

const read=(args)=>(dispatch, getState, {rpc})=>{
 const arguments=getState().some_arguments;
 return rpc.actual_read_returns_promise({...args, ...arguments});
}

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    每个 reducer 都可以访问它自己的状态切片,因此它不需要传递给它的任何已经存在于它自己的状态中的数据。当你有一个动作需要更新多个属于不同减速器的状态切片时,每个减速器都应该监听这个动作并分别修改自己的状态。这种 action 和 reducer 的解耦是我觉得 redux 非常强大的原因之一。

    因此,在我看来,最好的方法是调度一个诸如“READ”之类的操作,其中包含从 read 函数返回的任何内容。然后每个包含由于该操作而必须修改的状态的 reducer 将侦听“READ”操作,然后修改它自己的状态。

    希望这会有所帮助。

    【讨论】:

    • 感谢您的回复,我同意修改减速器中的状态是最明显的事情。但是,我在问题中提到“我不能将后处理逻辑放在reducer中,因为它可能会产生副作用”。这是基于 reducer 必须是纯函数的建议(例如,参见 redux.js.org/docs/introduction/ThreePrinciples.html)。就我而言,数据的后处理当然不是一个纯粹的功能,因为它依赖于来自其他多个来源的数据。所以我必须寻找在其他地方进行后处理的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2018-03-04
    • 2018-05-12
    • 2021-05-26
    • 2019-03-03
    • 2015-03-21
    相关资源
    最近更新 更多