Ant Design 4.0中的新版connect函数

Ant Design最近推出了4.0版本,其中我最喜欢的改动是connect函数/装饰器的语法糖,极大的降低了我这种智商欠费者的认知成本……

1 老版本中的connect

我们先看看旧版connect函数的官方示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from 'react';
import { connect } from 'dva';
import ProductList from '../components/ProductList';

const Products = ({ dispatch, products }) => {
function handleDelete(id) {
dispatch({
type: 'products/delete',
payload: id,
});
}

return (
<div>
<h2>List of Products</h2>
<ProductList onDelete={handleDelete} products={products} />
</div>
);
};

// export default Products;
export default connect(({ products }) => ({
products,
}))(Products);

最后三行的connect函数,第一个参数是mapStateToProps函数,用于将需要的部分state传递进组件Products。示例中虽然没写,但是connect还可以再传递一个参数mapDispatchToProps,用于将封装好的dispatch传递给组件Products

我原来经常被那一堆括号,和最后的(Products)搞晕,导致忘记最后的那一对括号……

2 新版的connect装饰器

上面的代码就变成了这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React from 'react';
import { connect } from 'dva';
import ProductList from '../components/ProductList';

const mapStateToProps = (state) => {
return { products: state.products }
};
const mapDispatchToProps = (dispatch) => {
return {
handleDelete: (id) => {
dispatch({ type: 'products/delete', payload: id });
},
};
};

@connect(mapStateToProps, mapDispatchToProps)
export default class Products extends Component {
render() {
return (
<div>
<h2>List of Products</h2>
<ProductList onDelete={this.props.handleDelete} products={this.props.products} />
</div>
);
}
}

mapStateToPropsmapDispatchToProps也都通过装饰器传入了组件的props属性,但是这样的写法确实极大的降低了认知负担。

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×