Reputation: 1114
I am new to redux and react-router. In the Product
component, I can access the productId, but how can I access the store? Or how can I pass the product to the component?
Reducer
const reducer = combineReducers({
products: (state = []) => state,
routing: routerReducer
});
const store = createStore(
reducer, {
products: [{
id: 1,
name: 'Product A',
price: 1000
}, {
id: 2,
name: 'Product B',
price: 2000
}]
}
);
Components
const Product = ({params}) => (
<div>
Id: {params.productId}
</div>
);
class Products extends React.Component {
render() {
return (
<div>
<h1>Products</h1>
<ul>
{this.props.children ||
this.props.products.map(product => (
<li key={product.id}>
<Link to={`/products/${product.id}`} >{product.name}</Link>
</li>))}
</ul>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
products: state.products
}
};
const ProductsContainer = connect(
mapStateToProps
)(Products)
Routes:
ReactDOM.render(
<Provider store={store}>
{ /* Tell the Router to use our enhanced history */ }
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="products" component={ProductsContainer}>
<Route path=":productId" component={Product}/>
</Route>
</Route>
</Router>
</Provider>,
document.getElementById('root')
);
Upvotes: 1
Views: 572
Reputation: 475
Product is a container. Because you put it in the route. So you should use the connect and mapStateToProps function to transmit the store, just like what you do in Products container.
Upvotes: 2