在React中为常见状态创建一个钩子

时间:2020-04-16 16:35:45

标签: reactjs react-hooks

我有一个由多个组件使用的通用小部件。每个使用公共组件的组件都必须具有相同的状态变量,我想知道是否以及如何能够将其抽象到自定义钩子中。这是常见状态:

const [
  { leftCount, rightCount, isActive },
  setState,
] = useState({
  leftCount: 0,
  rightCount: 0,
  isActive: false,
})

还有一些常用方法:

const handleLeftClick = () => {
  setState(state => ({
    ...state,
    leftCount: leftCount + 1,
  }))
}
const handleRightClick = () => {
  setState(state => ({
    ...state,
    rightCount: rightCount + 1,
  }))

...

1 个答案:

答案 0 :(得分:0)

使用react自定义钩子,抽象版本应如下所示(您要共享逻辑):

const useCommon = () => {
  const [{ leftCount, rightCount, isActive }, setState] = useState({
    leftCount: 0,
    rightCount: 0,
    isActive: false
  });

  // Rest of your logic 

  // Return everything you want (I just return a sample, You can return your handlers or anything else)
  return [{ leftCount, rightCount, isActive }, setState]; 
};