【发布时间】:2022-01-07 07:25:27
【问题描述】:
我需要一个堆栈来管理一些标签的状态。首先,我将它们声明为 ref 如下:const stack = React.useRef([]), const index = React.useRef(0),然后我访问堆栈并手动维护它。
之后,我尝试将它们抽象为一个独立的类:
import { Label } from '../interface/basic'
import { groupBy } from '../utils/categorys&colors'
export interface Can {
redo: boolean
undo: boolean
reset: boolean
save: boolean
}
export interface State extends Array<Label> {}
export class StateStack {
private stateStack: State[] = []
private index: number = 0
can: Can
constructor(initialState?: State) {
if (initialState) {
this.stateStack.push(initialState)
this.index = 1
}
this.updateCan()
}
reset() {
this.stateStack = []
this.index = 0
this.updateCan()
return this
}
nowState() {
this.updateCan()
return this.stateStack[this.index - 1]
}
nextState() {
this.index += this.can.redo ? 1 : 0
return this.nowState()
}
prevState() {
this.index -= this.can.undo ? 1 : 0
return this.nowState()
}
resetState() {
if (this.can.reset)
this.index = this.index !== 1 ? 1 : this.stateStack.length
return this.nowState()
}
pushState(newState: State) {
this.stateStack = this.stateStack.slice(0, this.index)
this.index = this.stateStack.push(newState)
return this.nowState()
}
updateCan() {
this.can = {
redo: this.index < this.stateStack.length,
undo: this.index > 1,
reset: this.stateStack.length > 1,
save: this.index > 1 || this.index < this.stateStack.length
}
}
groupedState() {
return this.nowState() ? groupBy(this.nowState(), 'categoryName') : {}
}
}
然后我在顶层声明一个这样的状态:const stateStack = useState(new StateStack()),在大多数情况下,它运行良好,但在重新渲染时出现了一些小问题。
所以我试图将它重构为一个钩子但失败了。有人可以帮我重建这个类吗?
【问题讨论】:
-
你问的是如何将一个类组件转换成一个React函数组件?
-
@DrewReese 实际上不是,这个问题更像是一些处理登录状态的自定义钩子的例子,但我不知道哪个是最佳实践,因为我只看到了一些例子使用 Ref 声明变量并使用“react-use”库中的更新钩子来触发重新渲染和一些使用减速器。这真的让我很困惑。
-
所以你不是想把类组件转换成函数组件?那你想做什么? React 钩子只能用于函数组件和其他自定义钩子。看起来你有一个初始任务,然后将这个类组件和逻辑转换为一个函数组件,以便它可以使用 React 钩子。
-
@DrewReese Emmm,不。我想定制一个可以存储堆栈并提供其句柄的钩子。下面的答案就是我想做的。
标签: reactjs typescript react-hooks