如何将 Reused Reducers Logic 连接到 React 组件中?

How to connect Reused Reducers Logic into React components?

我正在使用 here 描述的模式,它向我们展示了如何为其他类似目的重用 reducer 逻辑。

所以,我的 reducer 代码就像下面的代码:

function ContentFilterReducer(entity = ''){
    initialState.groupFilter = entity;
    return function ContentFilterReducer(state = initialState, action)
    {

        // is the entity that we want to update?
        if (action.item !== undefined && action.item.groupFilter !== entity)
            return state;

        switch (action.type) {
            case ContentFilterTypes.ADD_ITEM:
                return {
                    // we set the 
                    groupFilter: action.item.groupFilter,
                    listObjects : state.listObjects.push(new Map({
                        id: action.item.id,
                        description: action.item.description,
                        imgSrc: action.item.imgSrc
                    }))
                } 

            default:
                return state;
        }
    }
}

我的 combinedReducer 描述了每个用途的减速器,如下所示:

const SearchReducers = combineReducers({
    // contains all allowed filters to be selected
    UsersContentFilterReducer : ContentFilterReducer(Types.users),
    OrganizationsContentFilterReducer : ContentFilterReducer(Types.organizations)

})

一切正常,但我想知道如何使用 React-Redux[的 connect 函数在 React 组件中连接它?

正如我们所见,我可以定义 reducer 设置一个 entity(一个简单的字符,如 'a'、'o' 等),然后,调用特定的减速器,我只需要在我的操作中设置 entity 。现在,问题是如何 连接 特定表示组件的特定减速器?

下面的代码是我的 HOC 容器,将 reducer 连接到特定组件,但是,代码是旧版本,没有定义 reducer 应该调用什么。

const mapStateToProps = (state, action) => {
    return {
        contentList: ContentFilterReducer(state.ContentFilterReducer, action)
    }
}

/**
 * 
 * @param {contains the action that will be dispatched} dispatch 
 */
const mapDispatchToProps = (dispatch) => {
    return {
        onAddClick: (groupFilter, filterDescription, operator, value) => {
            dispatch(AddFilter(groupFilter, filterDescription, operator, value));
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ContentFilterField)

您没有连接减速器。您将 component 连接到 Redux store。我就不说我的州了xxxReducer,有点乱。

我不确定你的应用是什么样的,对于一个简单的案例,你只需要:(连接两个状态)

const mapStateToProps = (state) => {
  return {
    userContentList: state.SearchReducers.UsersContentFilterReducer,
    organizationContentList: state.SearchReducers.OrganizationsContentFilterReducer,
  }
}

如果你想根据组件的状态动态地在 usersContentorganizationsContent 之间切换,你需要的是一个 selector 函数。

这是官方的 redux 示例:https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/index.js#L10-L26

这些函数是选择器,你导入并使用它们来获得你想要的状态。

所以你将创建类似 getContentList 的东西,它接受像 Types.users

这样的 type
const mapStateToProps = (state) => {
  return {
    // suppose you save current type saved in SearchReducers.type
    contentList: getContentList(state.SearchReducers.type)
  }
}

还有,mapStateToProps的第二个参数是ownProps不是action