如何将状态传递给组件?
How to pass state to component?
我是 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')
);
产品是一个容器。因为你把它放在了路线中。
所以你应该使用 connect 和 mapStateToProps 函数来传输商店,就像你在 Products 容器中所做的那样。
我是 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')
);
产品是一个容器。因为你把它放在了路线中。 所以你应该使用 connect 和 mapStateToProps 函数来传输商店,就像你在 Products 容器中所做的那样。