1.弃用ComponentWillReceiveProps
- ComponentWillReceiveProps此API已过期,建议使用getDerivedFromState来替代
- getDerivedFromState是个静态方法,请参考这篇文章
- 多数情况下,我们使用ComponentWillReceiveProps的目的是为了对某一个prop进行复杂的处理,生成一个过程变量,以避免其他prop改变时,频繁进行重复处理。针对这种情况,最佳的方案是采用memoize-one,进行一次缓存。具体请参考CommontTable这个组件
// static getDerivedStateFromProps(props: mixedProps, state) {
// if (props.option !== state.option) {
// let { option: { colConfig, tableData, dicMap } } = props;
// let columns = CommonTable.getColumns(colConfig!);
// let dataSource = CommonTable.dataFormatHandler(tableData, colConfig!, dicMap);
// return { columns, dataSource, option: props.option };
// }
// return null;
// }
memColumns = memoize((colConfig) => CommonTable.getColumns(colConfig!));
memDataSource = memoize((tableData, colConfig, dicMap) => CommonTable.dataFormatHandler(tableData, colConfig!, dicMap));
render() {
const { option, ...restProps } = this.props;
const { colConfig, tableData, dicMap } = option
return (
<div ref={ele => this.tableEle = ele} style={{ height: '100%' }}>
{
!this.state.measureOk ? null :
<Table
rowKey={option.colConfig && option.colConfig.pKey || 'myTable'}
size={"small"}
{...restProps}
// dataSource={this.state.dataSource}
// columns={this.state.columns}
dataSource={this.memDataSource(tableData,colConfig,dicMap)}
columns={this.memColumns(colConfig)}
scroll={{ y: this.state.scollY, x: '100%' }}
loading={!this.state.measureOk}
/>
}
</div>
)
}
2. Class内部的方法顺序建议
建议按以下顺序来组织代码,具体请参考CommonTable组件:
//全局变量定义
constructor();
componentWillMount();
//...其他生命周期函数,按发生的时间次序
render();
//其他方法
3. 封装组件的props,使用class定义props,使用 new Class()来定义default props
具体请参考CommonTable组件.
4. 学会使用ts的混合类型
type mixedProps = CommonTableProps & TableProps<any>;
5. 不是所有的请求都需要走redux,dispatch,有可能更简洁
可以直接使用promise方法,或直接使用fetch,参考Role/table.tsx
6. reducer的最佳实践,你可能只需要一个reducer方法:updateState
参考Example/Curd/Model.ts
7. 学会使用全局常量定义
/** 通用正则 */
export const allRegx = {
/** 正负整数都支持 */
整数: /^-?\d+$/,
数字: /^-?\d+(\.\d+)?$/,
手机号: /^1[3|4|5|8][0-9]\d{4,8}$/ ,
固话: /^-?\d+(\.\d+)?$/,
身份证: /^\d{15}|\d{}18$/,
邮箱: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
}
8. 属性上尽量使用/***/来备注,可以被ts自动提示
9. 尽量使用pureComponent,并理解PureComponent
props不要使用嵌套太深和太复杂的对象结构,因为PureComponent只能做浅比较,了解一下shallowEqual
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || ! shallowEqual(inst.state, nextState);
}