我试图创建一个自定义钩子,该钩子会更新状态,而不是像类组件中的setState一样替换状态。它应该像这样工作:
渲染的一部分:
interface IExample {
foo: number
bar: string
}
const [state, setState] useCustomHook<IExample>({foo: 1, bar: 'aaa'})
在某些回调中:
setState({bar: 'bbb'}) // after everything settles, the state should be: {foo: 1, bar: 'bbb'}
尝试的解决方案(已更正,现在可以使用):
const isFunction = (value: any): value is Function => typeof value === 'function'
export default <T>(initialState: T | (() => T)):[T, (newState: Partial<T> | ((prevState: Partial<T>) => Partial<T>)) => void] => {
const [state, setState] = useState<Partial<T>>(initialState)
const setStateMerging = (newState: Partial<T> | ((prevState: Partial<T>) => Partial<T>)) => {
if (isFunction(newState)) {
setState((prevState) => ({ ...prevState, ...newState(prevState) }))
} else {
setState((prevState) => ({ ...prevState, ...newState }))
}
}
return [state, setStateMerging]
}
@Jonas Wilms回答后,问题已得到纠正。
答案 0 :(得分:2)
您的isFunction
必须是一名打字员:
const isFunction = (value: any): value is Function => typeof value === 'function'