如何在React with Typescript中的类组件中创建类似于setState的自定义钩子

时间:2020-08-23 13:06:00

标签: javascript reactjs typescript react-hooks

我试图创建一个自定义钩子,该钩子会更新状态,而不是像类组件中的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]
}

Here is a demo

@Jonas Wilms回答后,问题已得到纠正。

1 个答案:

答案 0 :(得分:2)

您的isFunction必须是一名打字员:

 const isFunction = (value: any): value is Function => typeof value === 'function'