如何将ReusedReducers逻辑连接到React组件中?

问题描述 投票:0回答:1

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

所以,我的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'等),并且,要调用特定的reducer,我只需要在我的中设置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)
reactjs redux react-redux
1个回答
1
投票

您没有连接减速器。您将一个组件连接到 Redux store。我不会命名我的状态

xxxReducer
,这有点令人困惑。

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

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

如果您想根据组件的状态在

usersContent
organizationsContent
之间动态切换,您需要的是
selector
函数。

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

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

因此,您将创建类似

getContentList
的内容,并且它接受像
type
 这样的 
Types.users

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

另外,

mapStateToProps
的第二个参数是
ownProps
而不是
action

© www.soinside.com 2019 - 2024. All rights reserved.