首页 > 解决方案 > 关于redux组件渲染方法的问题

问题描述

我有三个组件,它们都连接到 redux 存储并显示相同的状态,我们称之为x

并且三个连接的组件具有父子关系,例如:

- connect()(ComponentA)
  - connect()(ComponentB)
  - connect()(ComponentC)

ComponentB 和 ComponentC 都是 ComponentA 的子级

当我改变x连接的ComponentC的值时x,ComponentA和ComponentB的显示也发生了变化,但是ComponentB中的render方法调用了多少次?

理论上它应该调用两次(一次由父组件 A 调用,一次由自身调用),实际上它只调用一次。为什么?


还原代码:

function counter(initalState = { count: 0 }, action) {
  switch (action.type) {
    case "add":
      return Object.assign({}, { count: initalState.count + 1 });
    default:
      return initalState;
  }
}

const store = createStore(
  combineReducers({
    counter
  })
);

function mapStateToProps(state) {
  return {
    count: state.counter.count
  };
}

function mapDispatchToProps(dispatch) {
  return {
    add: function() {
      dispatch({
        type: "add"
      });
    }
  };
}

标签: reactjsredux

解决方案


推荐阅读