Answer the question
In order to leave comments, you need to log in
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}]
};
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question