react-redux:来自reducer的调度动作

时间:2019-01-09 18:52:13

标签: reactjs redux react-redux

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

我知道在redux中是不可能的,但是我想不出另一种选择。谁能给我任何建议/建议?

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

BuildingComponent

//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
      }
    }
  }

  ...

}

InfoDrawerComponent

//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 };
  }

  ...

}

这是我的状态布置方式

state = {

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

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

  ...

}

3 个答案:

答案 0 :(得分:2)

我过去所做的是使用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
        }
    }
};

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

答案 1 :(得分:1)

我建议让infoDrawer减速器监听相同的动作类型。如有必要,让调度动作的逻辑将建筑物状态中的其他信息放入动作对象。有关更多信息,请参见the Redux FAQ entry on sharing state between reducers

答案 2 :(得分:0)

您可以创建一个中间件,该中间件侦听要与之交互的操作类型,也可以使用可观察到的redux https://redux-observable.js.org/

相关问题