【问题标题】:React - Redux dispatch an action based on UI stateReact - Redux 基于 UI 状态调度一个动作
【发布时间】:2018-02-12 09:51:12
【问题描述】:

在我的 React 组件化简器状态中,我有一个 selectedTabIndex 属性,指定我的 UI 中当前处于活动状态的选项卡。

const deviceRankReducer = (state = {
    selectedIndex:1
},action) ={
   //...
}

在我的 Redux 操作中,我想根据选定的选项卡索引进行 AJAX 调用。

class MyActions extends ReduxActionsBase {
     sendRequest(){
          if(state.selectedIndex === 0){
             //make call to resource A
          }else{
             //make call to resource B
          }
     }
}

在不做出反模式决策的情况下与 ReduxActionsBase 共享信息的最佳做法是什么?

【问题讨论】:

    标签: javascript web redux react-redux reducers


    【解决方案1】:

    我建议使用redux-thunkredux-thunk 允许您调度条件和异步操作,并且您将可以访问您的操作创建器中的 Redux 状态。在您的情况下,动作创建者将是这样的

    function makeRequest() {
      return (dispatch, getState) => {
        const { selectedIndex } = getState();
    
        if(state.selectedIndex === 0){
          //make call to resource A
        }else{
          //make call to resource B
        }
      };
    }
    

    【讨论】:

    • 感谢回复,不加3rd方库可以吗?我在给定的环境中工作
    • redux-thunk 在 redux 应用程序中非常非常常用,没有它或没有类似的东西很难创建 redux 应用程序,但如果你不能安装任何 3rd 方库,你必须编写你自己的 Redux middleware: redux.js.org/docs/advanced/Middleware.html
    • redux-thunk 只有大约 12 行。如果您无法将其添加为 NPM 依赖项,只需将其复制粘贴到您的应用程序中即可。
    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2021-10-14
    • 2021-10-06
    • 2018-05-23
    • 1970-01-01
    • 2017-08-24
    • 2018-08-02
    相关资源
    最近更新 更多