Reputation: 1123
If I have a React component I am using twice, how do I send actions to the store to change the relevant value for one but not the other? E.g.,
//index.js
ReactDOM.render(
<Provider store={store}>
<div>
<ComponentContainer/>
<ComponentContainer/>
</div>
</Provider>,
document.getElementById('home')
);
//container.js
const mapStateToProps = (state) => ({
value: state.value,
});
const mapDispatchToProps = (dispatch) => ({
changeValue : (value) => {
dispatch(changeValueStore(value));
}
})
export default const ComponentContainer = connect(mapStatetoProps)(Component)
//component.js
export default function Component(props){
return (
<div onClick={handleChange(props.value++)}>
{props.value}
</div>
);
}
How do I isolate the two values of ComponentContainer with this structure? I realize I should be assigning the Containers ids to pass to the reducers, but I'm not sure where.
Upvotes: 1
Views: 111
Reputation: 62387
One solution is for the action object to have an additional field (say componentId
) which would tell the reducer which component this action concerns.
Call your action creator like this from within the component
<div onClick={handleChange(props.value++, props.componentId)}>
(Notice how componentId
is now a required prop) so
<Provider store={store}>
<div>
<ComponentContainer componentId="c1" />
<ComponentContainer componentId="c2"/>
</div>
</Provider>
You could actually reuse the reducer you already have just wrap it int another, which would call your reducer with appropriate branch of the state (matching the componentId
)
Upvotes: 1