将React JS生命周期方法迁移到Hooks

时间:2020-10-09 15:52:56

标签: reactjs react-hooks react-lifecycle

我正在尝试将componentDidUpdate转换为useEffects。我看过的示例很简单,但是由于componentDidUpdate似乎并没有太复杂。我需要进行条件更改,但不确定要使用prevProps vs道具上的条件来完成我真正需要做的事情

这是我想要转换的当前代码,以便可以从类移到功能组件。我添加了评论//这是我需要转换的地方。

import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
// import './ListingControl.css'
import { cssClasses, isDurationSame } from './util'
import { durationLike, isPlayerState } from './props'
import moment from 'moment'
import {
  SKIP_BACKWARD,
  FAST_BACKWARD,
  FORWARD,
  BACKWARD,
  FAST_FORWARD,
  SKIP_FORWARD,
  PAUSE,
  STOP,
  STEP_FORWARD,
  STEP_BACKWARD,
  DEFAULT_INTERVALS,
  DEFAULT_LENGTHS,
} from './constants'
import listingManager from './player'

const SYMBOLS = {
  [SKIP_BACKWARD]: '\u23ee',
  [FAST_BACKWARD]: '\u23ea',
  [FORWARD]: '\u23f4',
  [BACKWARD]: '\u23f4',
  [FAST_FORWARD]: '\u23e9',
  [SKIP_FORWARD]: '\u23ed',
  [PAUSE]: '\u23f8',
  [STOP]: '\u23f9',
  [STEP_FORWARD]: '\u23e9',
  [STEP_BACKWARD]: '\u23ea',
}

const SkipBackward = () => SYMBOLS[SKIP_BACKWARD]
const FastBackward = () => SYMBOLS[FAST_BACKWARD]
const Forward = () => SYMBOLS[FORWARD]
const Backward = () => (
  <div style={{ transform: 'scale(-1,1)' }}>{SYMBOLS[BACKWARD]}</div>
)
const FastForward = () => SYMBOLS[FAST_FORWARD]
const SkipForward = () => SYMBOLS[SKIP_FORWARD]
const Pause = () => SYMBOLS[PAUSE]
const Stop = () => SYMBOLS[STOP]
const StepForward = () => SYMBOLS[STEP_FORWARD]
const StepBackward = () => SYMBOLS[STEP_BACKWARD]

const NAME_MAPPING = {
  [SKIP_BACKWARD]: 'SkipBackward',
  [FAST_BACKWARD]: 'FastBackward',
  [BACKWARD]: 'Backward',
  [FORWARD]: 'Forward',
  [FAST_FORWARD]: 'FastForward',
  [SKIP_FORWARD]: 'SkipForward',
  [PAUSE]: 'Pause',
  [STOP]: 'Stop',
  [STEP_FORWARD]: 'StepForward',
  [STEP_BACKWARD]: 'StepBackward',
}

const CSS_CLASS_MAPPING = {
  [SKIP_BACKWARD]: 'skip-backward',
  [FAST_BACKWARD]: 'fast-backward',
  [BACKWARD]: 'backward',
  [FORWARD]: 'forward',
  [FAST_FORWARD]: 'fast-forward',
  [SKIP_FORWARD]: 'skip-forward',
  [PAUSE]: 'pause',
  [STOP]: 'stop',
  [STEP_FORWARD]: 'step-forward',
  [STEP_BACKWARD]: 'step-backward',
}

const DEFAULT_TIPS = {
  [SKIP_BACKWARD]: 'skip to left',
  [FAST_BACKWARD]: 'rewind',
  [BACKWARD]: 'play backward',
  [FORWARD]: 'play forward',
  [FAST_FORWARD]: 'fast-forward',
  [SKIP_FORWARD]: 'skip to right',
  [PAUSE]: 'pause',
  [STOP]: 'stop',
  [STEP_FORWARD]: 'forward 1 frame',
  [STEP_BACKWARD]: 'backward 1 frame',
}

function nextDuration(d, durations) {
  for (let i = 0; i < durations.length; i++) {
    if (isDurationSame(d, durations[i])) {
      return durations[(i + 1) % durations.length]
    }
  }

  return durations[0]
}

const ListingControl = (props) => {

    this.state = {}

  const [interval, setInterval] = useState ();
  const [length, setLength] = useState();
  const [playerState, setPlayerState] = useState();

    if (props.listingManager) {
      setInterval(props.listingManager.interval);
      setLength(props.listingManager.length);
      setPlayerState(props.listingManager.playerState);
      props.listingManager.reListControl(ListingControl)
    }

     
  componentDidUpdate(prevProps) {
    if (prevProps.listingManager !== this.props.listingManager) {
      if (prevProps.listingManager) {
        prevProps.listingManager.deListControl(this)
      }
      if (this.props.listingManager) {
        this.props.listingManager.reListControl(this)
      }
    }
  }

  //componentDidUpdate Replacement Area
   useEffect(() => {
    console.log('component updated!')

  }) 


//componentWillUnmountReplacement
  useEffect(() => {
    return () => {
      props.listingManager.deListControl(ListingControl)
    }
  }, []) // notice the empty array

  const onPlayerCommand = c =>{
    if (this.props.onPlayerCommand) {
      this.props.onPlayerCommand(c)
    }
    if (this.props.listingManager) {
      this.props.listingManager.execute(c)
    }
  }

  const onLengthChange = length => {
    if (this.props.onLengthChange) {
      this.props.onLengthChange(length)
    }
    if (this.props.listingManager) {
      this.props.listingManager.onLengthChange(length)
    }
  }

  const onIntervalChange = interval=> {
    if (this.props.onIntervalChange) {
      this.props.onIntervalChange(interval)
    }
    if (this.props.listingManager) {
      this.props.listingManager.onIntervalChange(interval)
    }
  }

  const getControlsState = () => {
    if (this.props.listingManager) {
      return this.state
    } else {
      return props
    }
  }

  render() {
    let { controls, titles } = this.props
    const { interval, length, playerState } = this.getControlsState()

    controls = {
      SkipBackward,
      FastBackward,
      Backward,
      Forward,
      FastForward,
      SkipForward,
      Pause,
      Stop,
      StepBackward,
      StepForward,
      ...controls,
    }

    titles = {
      ...DEFAULT_TIPS,
      ...titles,
    }

    const stopped = playerState === STOP
    const paused = playerState === PAUSE

    const controlDisabled = {
      [SKIP_BACKWARD]: stopped,
      [FAST_BACKWARD]: stopped,
      [BACKWARD]: false,
      [FORWARD]: false,
      [FAST_FORWARD]: stopped,
      [SKIP_FORWARD]: stopped,
      [PAUSE]: false,
      [STOP]: stopped,
      [STEP_FORWARD]: !paused,
      [STEP_BACKWARD]: !paused,
    }

    const controlProps = { controls, playerState, length, interval }

    const getControl = (c) => {
      const C = controls[NAME_MAPPING[c]]

      const p = {
        className: cssClasses(
          'control',
          CSS_CLASS_MAPPING[c],
          controlDisabled[c] ? 'disabled' : ''
        ),
        onClick: () => this.onPlayerCommand(c),
      }

      if (titles[c]) {
        p.title = titles[c]
      }

      return (
        <div {...p}>
          <C {...controlProps} />
        </div>
      )
    }

    return (
      <div className="timeline-player">
        <div className="controls">
          <div
            className={cssClasses('control', 'interval')}
            onClick={() =>
              this.onIntervalChange(nextDuration(interval, DEFAULT_INTERVALS))
            }
          >
            {moment.duration(interval).as('s')}s
          </div>
          <div className="control sep"> / </div>
          <div
            className={cssClasses(
              'control',
              'length',
              stopped ? '' : 'disabled'
            )}
            onClick={() =>
              stopped &&
              this.onLengthChange(nextDuration(length, DEFAULT_LENGTHS))
            }
          >
            {moment.duration(length).as('s')}s
          </div>
          {getControl(SKIP_BACKWARD)}
          {paused ? getControl(STEP_BACKWARD) : getControl(FAST_BACKWARD)}
          {playerState === BACKWARD
            ? getControl(PAUSE)
            : getControl(BACKWARD)}
          {playerState === FORWARD ? getControl(PAUSE) : getControl(FORWARD)}
          {paused ? getControl(STEP_FORWARD) : getControl(FAST_FORWARD)}
          {getControl(SKIP_FORWARD)}
          {getControl(STOP)}
        </div>
      </div>
    )
  }
}

ListingControl.propTypes = {
  controls: PropTypes.object,
  onPlayerCommand: PropTypes.func,
  playerState: isPlayerState(),
  length: durationLike(),
  onLengthChange: PropTypes.func,
  interval: durationLike(),
  onIntervalChange: PropTypes.func,
  titles: PropTypes.object,
  listingManager: PropTypes.instanceOf(listingManager),
}

ListingControl.defaultProps = {
  playerState: STOP,
  length: 'PT10S',
  interval: 100,
}
export default ListingControl

我不确定如何配合类似的示例

useEffect(() => {
    console.log('component updated!')
  }) 

2 个答案:

答案 0 :(得分:0)

使用useEffect时,您有第二个参数,它是具有依赖性的数组。任何对其进行更改的对象,useEffect都会侦听并重新执行主回调函数。 因此,您可以尝试以下方法:

useEffect(() => {
  // handle changes in prevProps.listingManager here
}, [prevProps.listingManager])

注意:挂钩在类组件中不起作用,它是为功能组件而制成的

更新:

考虑到props.listingManager将被更新,道具是read-only,您可以使用本地版本的道具来解决它。

const [localListingManager, setLocalListingManager] = useState();

props.listingManager更新后,您将使用新版本更新本地:

useEffect(() => {
  setLocalListingManager(props.listingManager)
}, [props.listingManager])

使用useEffect依赖项列表(即[props.listingManager]),您将始终具有新版本的props。这意味着由于prevProps变量,您不再需要localListingManager

答案 1 :(得分:0)

我认为在某些情况下迁移到功能组件很奇怪。 我以前在一个大型应用程序上做到了。我的建议是不要尝试将确切的代码转换为钩子,而是将确切的代码转换为混乱。 您应该了解想要从组件中获取的内容,并使用钩子将其重写,这更容易。钩子的行为不像类生命周期,但是您可以使用钩子来创建该行为,这在这里要说起来更加复杂,我认为您应该将它们用作工具,而不是作为类生命周期的替代品。