如何将状态传递给组件?

时间:2016-04-24 07:05:16

标签: react-router redux

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

1 个答案:

答案 0 :(得分:2)

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