react-redux:从减速器分派动作

Jes*_*inz 1 reactjs redux react-redux

我想从 BuildingComponent 的 reducer 函数分派一个动作来影响 InfoDrawer 的状态。

我知道这在 redux 中是不可能的,但我想不出替代方案。任何人都可以给我任何建议/推荐吗?

提前致谢。任何帮助表示赞赏。

建筑构件

//BuildingsState initial state
let initialState = {
  hasHighlight: false,
  buildings: [],
  visible: false,
}

// BuildingsState reducer
export function BuildingsState(state = initialState, action) {

  if (action.type === 'BUILDING_TOGGLE') {

    if(state.hasHighlight && state.visible) {

      // I WANT TO DISPATCH AN ACTION HERE
      // dispatch({ type: "ResetPOIs" })

    } else {
      return {
        ...state,
        visible: !state.visible
      }
    }
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

信息抽屉组件

//initial InfoDrawer State
const initialState = {
  open: false,
  textToDisplay: "",
  link: "",
}

//InfoDrawer reducer
export function InfoDrawerState ( state = initialState, action ) {

  if (action.type === "ResetPOIs") {
    return { textToDisplay: "", link: "", open: false };
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

这是我的状态的布局方式

state = {

  BuildingsState: {
    hasHighlight: false,
    buildings: [],
    visible: false
  }

  InfoDrawerState: {
    textToDisplay: "",
    link: "",
    open: false
  }

  ...

}
Run Code Online (Sandbox Code Playgroud)

Mat*_*t H 5

我过去所做的是使用 redux-thunk ( https://github.com/reduxjs/redux-thunk ) 并从我的 thunk 中分派动作。thunk 是同步评估的,因此您可以轻松获取原始操作被分派前后的状态。例如:

export const toggleBuilding = () => {
    return (dispatch, getState) => {
        dispatch({type: 'BUILDING_TOGGLE'});

        let {hasHighlight, visible} = getState();

        if(hasHighlight && visible) {
            //dispatch more stuff
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

另一种选择是设置对您的 redux 存储的订阅,以检查 hasHighlight 和visible 何时设置为true。您可以使用 connect() 或直接订阅从组件中执行此操作。