JSX
1、标签
具体以实际 eslint 规则和格式化工具为准,不用太过关心
(1)当标签没有子元素时,应使用自闭合的标签
// Good
<Component />
// Bad
<Component></Component>
(2) 有多行属性,关闭标签另起一行
<Component foo="foo" bar="bar" other="other" />
(3)闭合前留一个空格
<Component />
(4)JSX 标签最外层要用括号包裹
render() {
return (
<MyComponent>
// other line
</MyComponent>
)
}
2、对齐
// 推荐
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
/>
// 如果组件的属性可以放在一行(一个属性时)就保持在当前一行中
<Foo bar="bar" />
// 多行属性采用缩进
<Foo
superLongParam="bar"
anotherSuperLongParam="baz"
>
<Queen />
</Foo>
// 不推荐
<Foo superLongParam="bar"
anotherSuperLongParam="baz" />
3、引号
JSX 属性均使用双引号,其他的都使用单引号
// Good
<Foo bar="bar" />
<Foo style={{ left: '20px' }} />
// Bad
<Foo bar='bar' />
<Foo style={{ left: "20px" }} />
4、State
(1)初始化
应在构造函数中为 state 定义的内容做初始化
constructor(props) {
super(props)
this.state = {
// key:value
}
}
(2)修改
修改 state,需要调用 setState 方法
// Good
this.setState({ foo: 'foo' })
// bad
this.state.foo = 'bar'
(3)异步
出于性能考虑,React 可能会把多个 setState( ) 调用合并成一个调用;因为 this.props 和 this.state 可能会异步更新,所以这种场景下需要让 setState() 接收一个函数而不是一个对象 。
需要 state props 合并处理的
setState 不会返回 Promise 对象无法使用 await
// Good
this.setState((prevState, props) => {
return {
counter: prevState.counter + props.increment,
}
})
// Bad
this.setState({
counter: this.state.counter + this.props.increment,
})
依赖 state 更新结果的
// Good
this.setState(
{
counter: this.state.counter + 1,
},
() => {
this.doSomethingWithStateCounter()
}
)
// Bad
this.setState({
counter: this.state.counter + 1,
})
this.doSomethingWithStateCounter()
5、Props
(1)使用驼峰式定义 camelCase
// Good
<Foo userName="foo" onChange={this.handleChange} />
(2)属性值为 true,可省略
// Good
<Modal forceRender></Modal>
// Bad
<Modal forceRender={true}></Modal>
(3)为 Props 编写 propTypes
组件依赖有 Props 传参的应编写 propTypes 进行检查,此检查只在开发阶段起作用
import PropTypes from 'prop-types'
class FileUpload extends React.PureComponent {}
FileUpload.propTypes = {
uploadFileBtnText: PropTypes.string,
currentStep: PropTypes.number.isRequired,
downloadTempInfo: PropTypes.object.isRequired,
uploading: PropTypes.bool.isRequired,
uploadFile: PropTypes.func.isRequired,
progressTitle: PropTypes.string,
progressPercent: PropTypes.number.isRequired,
progressVisible: PropTypes.bool.isRequired,
handleModalVisible: PropTypes.func,
setCurrentStep: PropTypes.func.isRequired,
isExact: PropTypes.element,
maskClosable: PropTypes.bool,
preStep: PropTypes.func,
limitSize: PropTypes.number,
fileType: PropTypes.array,
ExtraContent: PropTypes.element,
}
(4)为非必须的 Props 指定 defaultProps
// 接上文
FileUpload.defaultProps = {
uploadFileBtnText: '提交',
progressTitle: '上传进度条',
handleModalVisible: () => {},
isExact: null,
maskClosable: false,
preStep: null,
limitSize: 0,
fileTye: [
// 默认限制类型,excel,传空数组表示不限制类型,或者传文件其他类型
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlsx',
'xls',
],
ExtraContent: null,
}
(5)普通组件在传递 Props 时少使用扩展运算符
扩展运算符经常把没必要的属性传递给 DOM
例外情况
- 高阶组件可以使用扩展运算符
高阶组件只是用来增强功能
function HOC(WrappedComponent) {
return class Proxy extends React.Component {
Proxy.propTypes = {
text: PropTypes.string,
isLoading: PropTypes.bool
};
render() {
return <WrappedComponent {...this.props} />
}
}
}
- 清楚扩展对象结构时才使用扩展运算符
export default function Foo {
const props = {
text: '',
isPublished: false
}
return (<div {...props} />);
}
- 筛选出不必要的属性再使用扩展运算符
// Good
render() {
const { irrelevantProp1,irrelevantProp2, ...relevantProps } = this.props;
return <WrappedComponent {...relevantProps} />
}
// Bad
render() {
return <WrappedComponent {...this.props} />
}
6、Refs
(1)尽量少用 Refs
(2)使用 createRef 少用回调
export default class MyComponent extends React.Component {
formRef = React.createRef()
render() {
return <Form form={formRef}></Form>
}
}
(3)跨组件访问子组件 Ref 使用 forwardRef
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps)
console.log('new props:', this.props)
}
render() {
const { forwardedRef, ...rest } = this.props
// 将自定义的 prop 属性 “forwardedRef” 定义为 ref
return <Component ref={forwardedRef} {...rest} />
}
}
// 注意 React.forwardRef 回调的第二个参数 “ref”。
// 我们可以将其作为常规 prop 属性传递给 LogProps,例如 “forwardedRef”
// 然后它就可以被挂载到被 LogProps 包裹的子组件上。
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />
})
}
(4)Redux Connect 携带子组件 Ref 对象
@connect(null, null, null, {
// react-redux 6.x版本以后
// 返回子组件的ref对象
forwardRef: true,
// react-redux 6.x版本以前
// 可以访问getWrappedInstance()获取子组件
withRef: true,
})
export default class MyComponent extends React.Component {
formRef = React.createRef()
render() {
return <Form form={formRef}></Form>
}
}
方法
(1)处理事件方法需要绑定上下文的需使用箭头函数
// Good
export default class MyComponent extends React.Component {
/*
*
*/
handleBtnClick = (e) => {
// doSomething
}
render() {
return (
<Button onClick={this.handleBtnClick}></Button>
);
}
}
// Bad
export default class MyComponent extends React.Component {
constructor(props) {
super(props)
// 经常修改或者忘了写
this.handleBtnClick = this.handleBtnClick.bind(this)
}
handleBtnClick(e) {
// doSomething
}
render() {
return (
<Button onClick={this.handleBtnClick}></Button>
);
}
}
// VeryBad
export default class MyComponent extends React.Component {
handleBtnClick(e){
// doSomething
}
render() {
return (
// 下面的写法每次会多创建一个方法造成资源浪费
<Button onClick={this.handleBtnClick.bind(this)}></Button>
<Button onClick={(e)=> {this.handleBtnClick(e)}}></Button>
);
}
}
分号
React 项目每句结尾要加;号
Context
当一个组件要跨层向子组件传参数时应使用 Context
代码编写顺序
// 装饰器
@connect()
@HOC('传参')
class Example extends Component {
// 静态属性
// 属性声明
formRef = React.createRef()
// 相当于计算属性但没有缓存效果
get selectItem() {}
// 构造函数
constructor(props) {
super(props);
this.state={}
}
// 从props中获取state,在constructor之后执行
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.type !== prevState.type) {
return {
type: nextProps.type,
};
}
return null;
}
// 声明周期钩子函数
// 按照它们执行的顺序
// 1. componentWillMount
// 2. componentWillReceiveProps
// 3. shouldComponentUpdate
// 4. componentDidMount 模块渲染后 通常获取数据 处理Dom事件
// 5. componentDidUpdate 关键参数变更后获取数据
// 6. componentWillUnmount 移除计时器, 解绑定Dom事件
// 获取数据
fetchInfo() {}
// 格式化数据方法 有共性后应抽取走
formatSomeItemIntoOtherItem () {}
// 事件函数/普通函数
handleClick = (e) => { ... }
// 最后,render 方法
render() { ... }
}
Example.defaultProps = {}
Example.propTypes = {}
export default Example
高阶组件
复用业务逻辑或增强子组件功能时应使用高阶组件
// 普通高阶组件
export default class HOCXxx extends React.PureComponent {
handleChange = (value) => {
this?.props?.handleChange(value.replace('foo', 'bar').toUpperCase())
}
// 加入自己的功能
render() {
// 绑定自己的功能
return <WrappedComponent onChange={this.handleChange} ...{props} />;
}
}
// 代参函数高阶组件,可用作装饰器
export default ({ variable }) => (WrappedComponent) => {
return class TableList extends PureComponent {
render() {
const props = this.props;
return <WrappedComponent {...props} />;
}
};
};
单向数据流和 state 状态
1、适宜使用单向数据流的情况
(1)业务页面可以配合 dva 使用单向数据流渲染
(2)需要保持状态的可以使用单向数据流
(3)全局共享的数据可以使用单向数据流
2、适宜使用 state 状态的情况
(1)组件应使用 state 管理自身状态
(2)可以多组件拆分的子组件应使用 Context 向下传递数据
(3)自定义表单控件应使用 state
渲染优化
(1)使用 PureComponent 和 immer.js
immer.js 实现了 immutable 规则正好对应 PureComponent 的优化渲染规则
(2)减少更新 props 和 state 的频率
(3)尽量在 render 方法中少创建新的对象和方法绑定
(4)计算属性应使用memoize-one
(5)hooks 中 应使用 useMemo,useCallback 缓存计算属性和方法
DVA
1、使用 effects type 可以轻松实现以下功能
{
effects: {
// 默认每次都执行
*fetchInfo(action, {call, put}) {
const response = yield call(api)
yield put({type , payload })
},
// takeLatest相当于只响应最后一次请求结果
latestFetchInfo: [
function* (action, { call, put }) {
const response = yield call(api);
return response;
},
{ type: 'takeLatest' },
],
// throttle 相当于10秒内只能触发一次uploadFile
uploadFile: [function* (action, {call, put}){
const response = yield call(api, action.payload);
return response;
}, {type: 'throttle', ms: 100000}],
// watcher 初始化时执行一次,后续的dispatch也不会触发
addWatcher: [
function*({ take, put, call }) {
console.log('addwatcher while');
while (true) {
console.log('addwatcher 执行到这里就不再执行了因为addWatcher只能被执行一次');
const { payload } = yield take('addWatcher');
yield call(delay, 100);
yield put({ type: 'add', payload });
}
},
{ type: 'watcher' }
],
}
}
2、使用 dva-model-extend 复用代码
dva-model-extend 对象扩展不支持深度扩展只能用简单对象属性
3、使用 immer.js 编写 reducer
immer.js 是 immutable.js 的简化版 可以结合 PureComponent 优化 react 渲染
import produce from 'immer'
export default {
reducers: {
setInitialValues: (state, { payload: { initialValues } }) =>
produce(state, draft => {
draft.searchForm.initialValues = initialValues
}),
},
}
immutable 常见问题
数组无法排序导致cannot assign to read only property '0' of object
错误
data.sort((a, b) => {
return a.x - b.x
})
// 解决 immutable 无法自己改自己的问题
const sortedData = [...data].sort((a, b) => {
return a.x - b.x
})
4、命名空间
默认不指定 namespace 则为该 model 文件名,使用 dva-model-extend 需指定 namespace,namespace 需全局唯一
5、dispatch 函数
dispatch 函数是异步的,dva 中的 dispatch 与 redux 中的有细节差别。最初扩展了一个 callback 用来做回调,dva 2.0 以后添加了 effect 返回 Promise, reducer 返回 action 的处理。我们推荐使用 async await 来处理 effect 和 reducer(虽然返回 action 但使用 await 也起作用) 返回的 Promise
// jsx
export default class MyComponent extends React.Component {
async componentDidMount() {
await dispatch({
type: 'specification/fetch',
})
}
}
// model
export default {
effects: {
*fetch(action, { call }) {
return yield call(api)
},
},
}
6、put 函数
put 函数 saga 提供的用来在 effect 内更新 reducer 的,但是很多时候为了实现 effect 复用有人用 put.resolve 同步调用 effect
export default {
effects: {
*fetchList(action, { call, put }) {
const response = yield call(api)
// 使用put.resolve可以实现同步调用
const data = yield put.resolve({
type: 'otherEffect',
payload: { data: response.data },
})
yield put({ type: 'reducerName', payload: { data } })
},
},
}
7、subscriptions
订阅,一般用来全局监听路由、鼠标、键盘、socket 连接,对象内的方法名称随意定义
subscriptions 在构建时会执行一次
export default {
subscriptions: {
onResize({dispatch}){
window.addEventListener('resize', () => {
dispatch({type: 'resize'})
})
},
onClick({dispatch}) {
document.addEventListener('click',() => {
//这里表示当鼠标点击时就会触发里面的dispatch命令,这里的save就是reducers中的方法名
dispatch({type: 'save'})
})
},
historyListen({dispatch, history}) {
history.listen((location, action)) => {
// 路由监听控制
}
},
},
};
8、dva/saga
dva/saga 包中导出了 react saga 的所有 api 方法,下面列出了比较有用的几个方法
import * as saga from 'dva/saga';
const {delay, effects} = saga;
const {all, apply, race, fork, take, takeLatest, cancel, cancelled } = effects;
// 延时
yield delay(5000)
Redux
1、中间件
Redux 中间件不能传递 null,必须是符合要求的函数
2、reducer
使用 immer.js 处理 reducer 避免使用展开扩展符设置 state
(1)普通 reducer
import produce from 'immer'
// Good
const reducer = (state = InitialState, action) => produce(state, draft) => {
switch(action.type) {
case 'TYPE_1':
draft.status = 'TYPE_1_STATUS'
break;
}
}
// 狗屎
const reducer = (state, action) => {
switch(action.type) {
case 'TYPE_1':
return {
...state,
status: action.status
}
}
}
(2) dva reducer
import produce from 'immer'
// Good
export default {
reducer: {
setTLTabList: (state, { payload: { list } }) =>
produce(state, draft => {
draft.tab.list = list
}),
},
}
// 狗屎
export default {
reducer: {
updateModelData(state, { payload }) {
return {
...state,
...payload,
}
},
},
}
3、refs
与dva refs相同
项目目录规范
普通目录和静态资源使用烤串 kebab-case 命名法
组件目录和组件名使用大驼峰 PascalCase 命名法
功能文件使用小驼峰 camelCase 命名法
dva model 使用 camelCase 命名