【问题标题】:Convert class component to functional components using hooks使用钩子将类组件转换为功能组件
【发布时间】:2020-07-12 16:03:16
【问题描述】:

我正在尝试使用钩子将此类组件转换为功能组件

import React, { Component, cloneElement } from 'react';

class Dialog extends Component {
    constructor(props) {
        super(props);
        this.id = uuid();       
   }
   render(){
     return ( <div>Hello Dialog</div> );
  }
}

此组件使用特定 ID 启动,因为我可能必须使用它们的多个实例。如果我使用功能组件,如何实现这一点?

【问题讨论】:

  • 您可以使用React.useRef。如果您的 ref current 为空,请尝试将其设置为 uuid(),否则意味着您已经有了一个,您可以跳过它。

标签: javascript reactjs react-hooks


【解决方案1】:

一种解决方案是使用useEffect 在第一次渲染时创建您的 ID,并将其存储在 state 中:

const Dialog = () => {
    const [id, setId] = useState(null);

    useEffect(() => {
        setId(uuid())
    }, [])

    return <div>Hello Dialog</div>
}

将空数组作为useEffect 的第二个参数使其无法多次触发。

但另一个非常简单的解决方案可能是……在您的组件之外创建它:

const id = uuid();

const Dialog = () => {
    return <div>Hello Dialog</div>
}

【讨论】:

  • 也可以是const [id, setId] = useState(uuid())
  • @norbitrial 好吧,我考虑过,但这意味着useState 钩子将在每次渲染时使用不同的值调用,因为uuid 每次都会执行。我通常不应该有任何副作用,但由于我不确定,我没有包括它
  • 我猜如果你将一个值传递给useState,那么它将一直保存到组件的生命周期,所以从技术上讲,它不会在渲染时改变。一旦调用setId,它将被更改。
  • 避免使用这种极其简单的解决方案,除非您确定不会同时安装一个以上的“Dialog”组件,或者 Id 的随机性无关紧要(在这种情况下,您不必使用 uuid)。
  • 另请注意,使用此 useEffect 方法,由于 useEffect 在渲染后运行,因此第一次渲染时 id 将为空。
【解决方案2】:

您可以将其存储在状态中:

const [id] = useState(uuid()); // uuid will be called in every render but only the first one will be used for initiation 

// or using lazy initial state
const [id] = useState(() => uuid()); // uuid will only be called once for initiation 

你也可以将它存储在 React ref:

const id = useRef(null);
if(!id.current) {
    // initialise 
    id.current = uuid();
}
// To access it’s value
console.log(id.current);

【讨论】:

    【解决方案3】:

    任何实例属性都几乎成为 ref,在这种情况下,您将访问 idRef.current 以获取 id

    function Dialog() {
      const idRef = useRef(uuid())
      return <div>Hello Dialog</div>
    }
    

    【讨论】:

      【解决方案4】:

      谢谢大家,您的解决方案运行良好。我也尝试了这个解决方案,我也觉得没问题:用Dialog.id 替换this.id。这个解决方案有什么缺点吗?

      【讨论】:

        猜你喜欢
        • 2020-06-06
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2020-01-29
        • 2020-11-30
        • 2020-12-21
        • 2019-07-11
        相关资源
        最近更新 更多