在两个Redux Reducers / States之间共享数据

时间:2016-01-10 22:25:18

标签: javascript redux

这是两个州/减少者之间数据共享的合理解决方案吗?

//combineReducers
function coreReducer(state = {}, action){

    let filtersState = filters(state.filters, action);
    let eventsState = events(state.events, action, { filters: filtersState});

    return { events: eventsState, filters : filtersState};

}

export const rootReducer = combineReducers(
    {
        core  : coreReducer,
        users
    }
);

如果是这样,如果对同一个调度事件和第二个减少函数的回答都取决于第一个的新状态,那么如何保证执行reducer函数的顺序?

我们假设我们发送了一个SET_FILTER事件,该事件会附加到过滤器商店中的activeFilters集合中,之后会根据activeFilters值更改事件存储中项目的可见性。

//ActiveFilters reducer
function filtersActions(state = {}, action){

    switch (action.type) {
        case SET_FILTER:
            return Object.assign({}, state, {
                [action.filterType]: action.filter
            })
        case REMOVE_FILTER:
            var temp = Object.assign({}, state);
            delete temp[action.filterType];
            return temp;

        case REMOVE_ALL_FILTERS:
            return {};

        default:
            return state
    }
}

我想我找到了答案 - 计算派生数据 - 重新选择

http://redux.js.org/docs/recipes/ComputingDerivedData.html

2 个答案:

答案 0 :(得分:0)

/--------container--------/
import {getGroupsAndMembers} from '../reducers'
const mapStateToProps = (state) => {
  return {
    inputValue: state.router.location.pathname.substring(1),
    initialState: getGroupsAndMembers(state) <-- this one
 }
}


/--------reducers--------/
export function getGroupsAndMembers(state){
   let { groups, members } = JSON.parse(state)
   response = {groups, members}
   return response;
}


GroupsContainer.propTypes = {
 //React Redux injection
 pushState: PropTypes.func.isRequired,
 // Injected by React Router
 children: PropTypes.node,
 initialState:PropTypes.object,
}

请勿忘记遵循&#39; connect&#39;

的指导原则
export default connect(mapStateToProps,{ pushState })(GroupsContainer)

答案 1 :(得分:0)

如果你有两个reducer,一个依赖于第一个的一个值,你只需要仔细更新它们,最好的解决方案就是使用一个特殊的函数,它将首先设置过滤,然后查询相应的事件。另外,请记住,如果事件提取是异步操作,您还应该基于过滤类型进行嵌套 - 否则可能存在竞争条件,并且您将有错误的事件。

I have created a library redux-tiles处理raw redux的详细程度,所以我将在这个例子中使用它:

import { createSyncTile, createTile } from 'redux-tiles';

const filtering = createSyncTile({
  type: ['ui', 'filtering'],
  fn: ({ params }) => params.type,
});

const events = createTile({
  type: ['api', 'events'],
  fn: ({ api, params }) => api.get('/events', { type: params.type }),
  nesting: ({ type }) => [type],
});

// this function will just fetch events, but we will connect to apiEvents
// and filter by type
const fetchEvents = createTile({
  type: ['api', 'fetchEvents'],
  fn: ({ selectors, getState, dispatch, actions }) => {
    const type = selectors.ui.filtering(getState());
    return dispatch(actions.api.events({ type }));
  },
});