custom hook setState forceUpdate
npm install @toolkitss/custom-hook> some useful custom hook
``zsh`
$ npm i -g npm
$ npm i --save @toolkitss/custom-hook
`zsh`
$ yarn add @toolkitss/custom-hook
`tsx
import React, { useRef } from 'react'
import { useSetState, useForceUpdate, useErrorBoundary } from '@toolkitss/custom-hook'
import { Input, Button } from 'antd'
interface IState {
age: number
name: string
}
export const SetState: React.FC = () => {
/* init setState /
const [state, setState] = useSetState
name: 'sunny',
age: 18,
}, () => {
console.log('init')
})
/* 受控组件 /
const edit = (e: React.ChangeEvent
const val = e.target.value
setState({
name: val
}, () => {
/* 更新结束后回调,可不传 /
console.log('updated')
})
}
/* 通过函数去更新state /
const update = () => {
setState((prevState) => {
return {
age: prevState.age + 1
}
/* 更新结束后回调 /
}, () => {
console.log('updated2222')
})
}
return (
{state.name}
{state.age}
)
}
export const ForceUpdate: React.FC = () => {
const number = useRef
const [, forceUpdate] = useForceUpdate()
const add = () => {
number.current = ++number.current
}
// 测试强制更新
const testForceUpdate = () => {
forceUpdate()
}
return (
// @ts-ignore
const ErrorC = () =>
export const ErrorBoundaryTest: React.FC = () => {
const { captureError, ErrorBoundary } = useErrorBoundary()
console.log(captureError)
return (
``