【问题标题】:In redux combineReducers is it correct that all reducers are called?在 redux combineReducers 中调用所有 reducer 是否正确?
【发布时间】:2020-03-04 23:14:43
【问题描述】:

我有 2 个减速器(计数和搜索),我已经组合了它们。当搜索组件调度时,两个 reducer 都会被调用。

  1. 这是调用所有减速器的预期行为吗?
  2. 或者,是否应该只调用最具体的 reducer(即搜索)?我必须怎么做才能只调用最具体的减速器?

这里是搜索、计数和组合减速器

const initialState = {url:'...'};
function search(state = initialState, action) {
  if (action.type === 'SEARCH') {
    ...
    return state;
  }
  return state;
}
export default search;

.

const initialState = 0;
function count(state = initialState, action) {
  if (action.type === 'INCREMENT') {
    return state + 1;
  }
  if (action.type === 'DECREMENT') {
    return state - 1;
  }
  return state;
}
export default count;

.

import CountReducer from './CountReducer.js';
import SearchReducer from './ApiReducer.js';
import { combineReducers } from 'redux'

const reduce = combineReducers({
  count: CountReducer,
  search: SearchReducer
});
export default reduce;

搜索组件如下所示

import React, { Component } from 'react';
import { onSearch as onSearchAction } from '../store/actions/Actions.js';
import { connect } from 'react-redux';

class Search extends Component {
  render() {
    return (
      <>
      ....
      </>
    );
  }
}

const mapStateToProps = (state) => {
  return { url: state.url };
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return { onSearch: () => dispatch(onSearchAction()) };
};

const ConnectedSearch = connect(mapStateToProps, mapDispatchToProps)(Search);

export default ConnectedSearch;

这里是搜索操作

export function onSearch() {
  return {
    type: "SEARCH",
    url: '...'
  }
}

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    这是所有 reducer 都被调用的预期行为吗?

    是的。

    我必须怎么做才能只调用最具体的 reducer?

    好吧,您可以编写一个自定义减速器来做到这一点,但我不确定有什么好处。大概你会编写代码说“如果是这个动作,或者这个动作,或者这个动作然后调用reducer 1;否则调用reducer 2”。但是检查动作类型是 reducer 1 已经在做的工作,所以你只是在复制逻辑。为什么不直接调用两个 reducer,让它们处理或忽略它们关心或不关心的任何事情?

    【讨论】:

    • 这对于大型应用程序来说可能是个问题,因为在这种情况下,每个 reducer 中的所有操作类型都必须不同,否则您可能会出现意外行为。
    猜你喜欢
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2019-01-15
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多