gpt4 book ai didi

javascript - 我可以在 connect redux 中传递多个组件吗

转载 作者:行者123 更新时间:2023-11-30 09:17:11 26 4
gpt4 key购买 nike

我想要一个智能组件/容器来处理产品实体的 CRUD 操作,我有以下代码:

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);

当我尝试从 App 组件调用时,它总是出现

知道如何制作它以便我可以从应用程序的任何位置导出 ListProducts、AddProduct 和调用。

最佳答案

您不能通过一次调用 connect 同时返回多个组件,请记住您是 export default 并且您应该只返回一个函数/组件,记住 connect 一次只返回一个组件,所以你可以这样做

export default {
ListProduct: connect(mapStateToProps)(ListProducts),
AddProduct: connect(mapStateToProps)(AddProduct)
}

所以在导入组件的时候可以做

import Components from ‘.../your/path’;
class MyView extends React.Component{
render(){
return <Components.ListProducts/>
}
}

关于javascript - 我可以在 connect redux 中传递多个组件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54272542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com