考虑一个React& Redux环境,组件接收某些状态。让我们使用以下示例:
state = {
users: ['bob', 'alice'],
history: {param: 1},
releases: [1, 2],
categories: [1, 2, 3],
store: {dispatch: () => (), subscribe: () => ()},
contact: {message: ""},
hosts: ['company1', 'company2'],
experiences: ['xp1', 'xp2'],
}
现在,我们按照以下方式编写组件:
import React, {Component} from "react";
import {connect} from "react-redux";
@connect(state => ({
hosts: state.hosts,
experiences: state.experiences,
categories: state.categories,
}))
export default class Home extends Component {
...
}
我一直试图想办法减少传递给 connect 的状态映射函数的大小。以下是一些例子:
@connect(({hosts, experiences, categories}) => ({hosts, experiences, categories})
@connect(state => _.pick(state, ['hosts', 'experiences', 'categories'])
@connect(({users, history, releases, store, contact, ...rest}) => rest)
没有令人满意的可读性和DRY智慧。 为什么我们有一个扩展和休息运算符,但没有办法减少这种冗余映射?类似于以下示例之一:
@connect(({hosts, experiences, categories}) => ...)
@connect(...({hosts, experiences, categories}))
@connect(=> ({hosts, experiences, categories}))
@connect(({hosts, experiences, categories}))
会更简单。 可能会有一种我不知道的更好的写作风格吗?