反应挂钩函数没有看到正确的状态值

时间:2020-07-16 15:35:00

标签: javascript reactjs typescript react-hooks react-state

我有一个名为useElements的钩子,它被称为一次。它具有一些状态并返回诸如updateElementcreateElement之类的方法。首先触发创建元素。它使用简单对象设置editable状态。接下来,触发更新。我不知道为什么,它没有看到我先前设置的{id}的状态。我不断得到null。看起来像个虫子

import { useState } from 'react'
import { Element, ToolType } from '../types'

export const useElements = () => {
  const [editable, setEditable] = useState<Element | null>(null)

  const createElement = (type: ToolType) => {
    const element: Element = {
      id: Math.random().toString(36)
    }

    setEditable(element)
  }

  const updateElement = (updates: Partial<Element>) => {
    console.log(editable) // always null
  }

  return {
    createElement,
    updateElement
  }
}

我触发钩子返回的函数的文件:


    import { useState } from 'react'
    import {  drawSelection } from '../drawing'
    import type { Tool, Element, Point, ToolType } from '../types'
    
    interface Params {
      createElement(type: ToolType): void
      updateElement(updates: Partial<Element>): void
    }
    
    export const useTools = ({ createElement, updateElement }: Params) => {
      const createElementAction = (type: ToolType) => (from: Point) => {
        createElement(type)
        updateElement({ from, to: from }) 
      }
    
      const updateElementAction = (from: Point, to: Point) => {
        updateElement({ from, to })
      }
    
      const tools: Tool[] = [
        {
          type: 'select',
          draw: drawSelection, // some canvas drawing function
          actions: {
            onMouseDown: [createElementAction('select')],
            onMouseMove: [updateElementAction],
            onMouseUp: [updateElementAction]
          }
        }
      ]
    
      const [tool, setTool] = useState<Tool>(tools[0])
    
      return {
        tool,
        tools,
        setTool
      }
    }

接下来,将动作onMouseMoveonMouseUponMouseDown绑定到canvas元素,因此在鼠标事件期间会调用它们

0 个答案:

没有答案