使用 React 钩子时的公共属性

时间:2021-03-31 18:45:43

标签: react-hooks

启动组件可以新建一个类并设置其中一些公共属性的值,以便稍后在同一类的方法中使用。

钩子组件中的 this 等价物是什么?这些属性是否应该添加到上下文中并从那里读取?有没有更简单的选择?

谢谢

1 个答案:

答案 0 :(得分:0)

如果这是常量属性,您可以在组件内部或外部定义常量。

const noOfItems = 5

const Comp = () => {
  const items = 'cats'
  
  return (
    <div>{noOfItems} {items }></div>
  )
}

如果值可以更改,并且更改它们会导致重新渲染,那么您应该使用 useStateuseReducer

const Comp = ({ items }) => {
  const [noOfItems, setNoOfItems] = useState(0)
  
  return (
    <>
      <div>{noOfItems} {items}></div>
      <button onClick={() => setNoOfItems(x => x + 1)}>
        Add Items
      </button>
    </>
  )
}

如果你想改变它,但改变它不会导致重新渲染,你可以用 useRef 这样做:

const Comp = ({ items, doSomething }) => {
  const [noOfItems, setNoOfItems] = useState(0)
  const fn = useRef() // fn would be preserved between renders, and mutating it won't cause re-renders

  useEffect(() => {
    fn.current = doSomething // changing this won't cause a re-render
  });

  useEffect(() => {
    fn.current(noOfItems)
  }, [noOfItems])

  return (
    <>
      <div>{noOfItems} {items}></div>
      <button onClick={() => setNoOfItems(x => x + 1)}>
        Add Items
      </button>
    </>
  )
}

虽然不是公开的,但您也可以将变量(和常量)保存在闭包中——例如 useEffect,只要它不被再次调用:

const Comp = ({ items }) => {
  const [noOfItems, setNoOfItems] = useState(0)

  useEffect(() => {
    const interval = setInterval(() => /* do something */) // the interval would preserved in the closure at it ins't called again

    return () => clearInterval(interval)
  }, [])

  return (
    <>
      <div>{noOfItems} {items}></div>
      <button onClick={() => setNoOfItems(x => x + 1)}>
        Add Items
      </button>
    </>
  )
}