Miz*_*lul 1 javascript reactjs react-redux
I would like to have a smart component/container that handles CRUD operations for Product entity and I have the following code:
function productContainerRender(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
this.fetchProducts = this.fetchProducts.bind(this);
}
fetchProducts = (page) => {
this.props.dispatch(fetchProductsBegin());
productsApi.getAll(page)
.then(response => {
if (response.data) {
this.props.dispatch(fetchProductsSuccess(response.data._embedded.companies));
} else {
this.props.dispatch(fetchProductsFailure({message: "Fetching products failed"}));
}
});
};
componentDidMount() {
// this.fetchProducts(1);
}
render() {
// ... and renders the wrapped component with the fresh data!
// Notice that we pass through any additional props
return <WrappedComponent {...this.props} fetchProducts={this.fetchProducts} />;
}
}
}
const productSelector = createSelector(
state => state.products,
items => items,
loading => loading,
error => error,
);
const mapStateToProps = createSelector(
productSelector,
(products) => ({
products,
})
);
const ListProducts = productContainerRender(
ListProductComponent
);
const AddProduct = productContainerRender(
AddProductComponent
);
export default connect(mapStateToProps)(ListProducts,AddProduct);
Run Code Online (Sandbox Code Playgroud)
When I try to call from App component, it always shows up
Any idea how to make it so I can export both ListProducts,AddProduct and call from anywhere on the app.
You can’t return multiple component at the same time with one call connect, remember that you are export default and you should return only one single function/component, remember that connect only return one single component at time, so the way you can do it is like
export default {
ListProduct: connect(mapStateToProps)(ListProducts),
AddProduct: connect(mapStateToProps)(AddProduct)
}
Run Code Online (Sandbox Code Playgroud)
So when importing the components you can do
import Components from ‘.../your/path’;
class MyView extends React.Component{
render(){
return <Components.ListProducts/>
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
You can only pass one Component to connect. So, instead, you’d have to do two connects:
const ConnectedListProducts = connect(mapStateToProps)(ListProducts)
const ConnectedAddProduct = connect(mapStateToProps)(AddProduct)
Run Code Online (Sandbox Code Playgroud)
Since you can have only one default export, you‘d have to use named export in this case or split up those two components in two files.
| 归档时间: |
|
| 查看次数: |
6670 次 |
| 最近记录: |