1.0.0 • Published 4 years ago
@zjxpcyc/with-function v1.0.0
with-function
跟 use-async 是同一个问题, 一个场景的业务代码被分散在各处。React 的 Function Componet 与 Hook 的结合基本上可以完美解决这个痛点。但是我们在实际执行过程中发现, 如果滥用 Hook , 会引来一系列的性能问题。而且无法使用 shouldComponentUpdate 或者 forceUpdate 这种类似的处理, 你必须使用各种类似 hack 的写法来达到目的。
其实 vue3 已经很好的解决我遇到的问题。只是我们的项目绝大部分都是 React 的, 没有机会转 vue3 .
于是自己结合 Hook 及 HOC 的思想封装了本工具
安装
npm install -S @zjxpcyc/with-function
使用
import React from 'react'
import withFunction from '@zjxpcyc/with-function'
@withFunction(React.Component)
function Foo(methods) {
// code here
}
函数格式
默认情况下会将当前函数的名称(如果是大写字母开头)作为组件名, 当然也可以用 displayName
方法进行自定义
参数
| 参数 | 类型 | 说明 |
|---|---|---|
| methods | object | 如下 |
| handler | object | 当前组件实例的 handler
, 就是 this
|
methods 属性列表
- forceUpdate
- setState
- componentDidMount
- shouldComponentUpdate
- getSnapshotBeforeUpdate
- componentDidUpdate
- componentDidCatch
- componentWillUnmount
- displayName
- defaultProps
return
必须返回一个 render
函数
示例
import React from 'react'
import withFunction from '@zjxpcyc/with-function'
// demo1
function Demo1(methods){
// devtool 里面 当前组件名称为 Demo1
this.state = {
count: 0
}
return () => {
// 此处可以使用 this
const { count } = this.state
return <div onClick={() => this.setState({ count: count + 1 })}>{count}</count>
}
})
// 如果需要导出
export default withFunction(React.Component)(Demo1)
// demo2
const useFunction = withFunction(React.PureComponent)
export default useFunction(({ setState, componentDidMount, displayName }, t) => {
// devtool 里面 当前组件名称为 Demo2
displayName('Demo2')
setState({
count: 0
})
// 也可以
t.state = {
count: 0
}
componentDidMount(() => {
// 此处进行一些 componentDidMount 周期的事情
// 比如 fetch data
})
return () => {
// 访问示例, 必须用 t
const { count } = t.state
return <div onClick={() => setState({ count: count + 1 })}>{count}</count>
}
})
thanks
1.0.0
4 years ago