B
B
bernex2016-12-18 17:20:04
React
bernex, 2016-12-18 17:20:04

With React and Redux, can't make separate components?

For example, I have a tree and I want to use it in 5 places. Because store one for the whole application, it turns out reducers will have to write different each time?
Those. it will not be possible to make a component and assign the values ​​of one to one key - as it is recommended not to nest in the store.

const initialState = {
    treeOneActiveItem: 'none',
    treeItems  : [{id:1, name:'ddd', parent_id:0}],
    treeTwoActiveItem: 'none',
    treeTwoItems  : [{id:1, name:'ddd', parent_id:0}]
};

And accordingly, I write the view components of the react once, is it really possible to copy-paste the rest? Or do not understand something still. The component model is familiar with classes and ordinary events, where everything is inside the class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2016-12-19
@bernex

I would somehow organize the data like this. Also, read about state normalization .

// store

const initalState = {
  treesById: {},
  activeByTreeId: {},
};

const treesReducer = (state, action) => {
  switch (action.type) {
    // store.dispatch({ type: 'ADD_TREE', id: 'users', tree: [...] })
    case 'ADD_TREE':
      return {
        ...state,
        treesById: {
          ...state.treesById,
          [action.id]: action.tree,
        },
      };

    // store.dispatch({ type: 'SET_ACTIVE', id: 'users', value: 5 })
    case 'SET_ACTIVE':
      return {
        ...state,
        activeByTreeId: {
          ...state.activeByTreeId,
          [action.id]: action.value,
        },
      };

    default:
      return state;
  }
};

// dumb component aka presenter

const Tree = ({ items, active }) => {
  return (
    <div className="tree-items">
      {items.map((item) => (
        <TreeItem
          key={item.id}
          item={item}
          isActive={item.id === active}
        />
      ))}
    </div>
  );
};

// smart component aka container

// (state, ownProps)
const mapStateToProps = ({ trees }, { treeId }) => {
  return {
    items: trees.treesById[treeId] || [],
    active: trees.activeByTreeId[treeId],
  };
};

// use in any component, e.g. Sidebar (presenter)
// props are passed from container

const Sidebar = () => {
  return (
    <div className="sidebar">
      <TreeContainer treeId="sidebar" />
    </div>
  );
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question