2016-04-24 95 views
1

我是redux和react-router的新手。在Product组件中,我可以访问productId,但是如何访问商店?或者我如何将产品传递给组件?如何将状态传递给组件?

减速器

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 
    }] 
    } 
); 

组件

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) 

途径:

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') 
); 

回答

2

产品是一个容器。因为你把它放在路线上。 因此,您应该使用connect和mapStateToProps函数来传输商店,就像您在产品容器中所做的一样。

+0

谢谢。因为最初我认为一个容器(即ProductsContainer)不能是另一个容器的父级。 – franziga

相关问题