【问题标题】:How to pass state to component?如何将状态传递给组件?
【发布时间】:2016-08-17 15:29:24
【问题描述】:

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

【问题讨论】:

    标签: react-router redux


    【解决方案1】:

    产品是一个容器。因为你把它放在了路由中。 所以你应该使用 connect 和 mapStateToProps 函数来传输 store,就像你在 Products 容器中所做的一样。

    【讨论】:

    • 谢谢。因为最初我认为一个容器(即 ProductsContainer)不能是另一个容器的父级。
    猜你喜欢
    • 1970-01-01
    • 2018-01-15
    • 2019-08-15
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2014-12-18
    • 2017-05-31
    相关资源
    最近更新 更多