ProductDetailContainer
и комнонент для отрисовки ProductDetail
. При componentDidMount у меня отсылается dispatch на action который делает запрос на получение данных.import { fetchingError, receiveData, fetching } from "../common";
import store from "../../store/store";
import ProductsService from "../../config/productService";
export const getProductDetail = id => async dispatch => {
dispatch(fetching());
return await ProductsService.getProductById(id)
.then(data => dispatch(receiveData(data)))
.catch(error => dispatch(fetchingError(error)));
};
export const dispatchGetProductDetailWired = payload => {
getProductDetail(payload)(store.dispatch);
};
import React, { Component } from "react";
import { connect } from "react-redux";
import { dispatchGetProductDetailWired } from "../../actions/productDetail/productDetail";
import LoadingPlaceholder from "react-loading-placeholder";
import ProductDetail from "../../components/ProductDetail/ProductDetail";
class ProductDetailContainer extends Component {
componentWillMount() {
const { id } = this.props.match.params;
dispatchGetProductDetailWired(id);
}
render() {
const { fetched, fetching, data } = this.props.productDetail;
return (
<div>
{fetched && !fetching ? (
<ProductDetail product={data} />
) : (
<LoadingPlaceholder
numberOfRows={10}
heightOfRows={40}
spaceBetween={10}
/>
)}
</div>
);
}
}
const mapStateToProps = state => {
return {
productDetail: state.products
};
};
export default connect(mapStateToProps)(ProductDetailContainer);
import React, { Component } from "react";
import TableComponent from "../Table/Table";
export default class ProductDetail extends Component {
render() {
console.log(this.props); // 2 раза вызывается при fetched true
return (
<React.Fragment>
<h2>{this.props.product.name}</h2> // не могу работать, т.к они еще не видимы при 1 запросе
{/* <TableComponent productInfo={data} /> */}
</React.Fragment>
);
}
}
export const getProductDetail = id => async dispatch => {
try {
dispatch(fetching());
const data = await ProductsService.getProductById(id);
dispatch(receiveData(data));
} catch (error) {
dispatch(fetchingError(error);
}
};
class ProductDetailContainer extends Component {
componentWillMount() {
const { match: { params: { id } }, getProductDetail } = this.props;
getProductDetail(id);
}
/* ... */
}
const mapStateToProps = state => ({
productDetail: state.products,
});
const matchDispatchToProps = {
getProductDetail,
}
export default connect(mapStateToProps, matchDispatchToProps)(ProductDetailContainer);