以这种方式使用useEffect有任何问题吗?

时间:2019-08-29 05:33:40

标签: reactjs

以这种方式使用useHooks处理componentDidMount和componentDidUpdate是否存在潜在问题?

这里有两个目标:

  1. 使用一个useEffect处理componentDidMountcomponentDidUpdate

  2. 无需传入第二个参数(通常是带有props的数组)

const once = useRef(false)
useEffect(() => {

    if(once.current === false){
        once.current = true
        // do things as were in componentDidMount
        return
    }

    // do things as were in componentDidUpdate

    // clean up
    return () => {
        //
    }
}) // <- no need to pass in 2nd argument

2 个答案:

答案 0 :(得分:0)

它没有问题,但是如果任何道具或状态值将改变,则useEffect将不会在重新渲染组件时加载。

因此最好在依赖于值变化时使用第二个参数。

const once = useRef(false)
useEffect(() => {

    if(once.current === false){
        once.current = true
        // do things as were in componentDidMount
        return
    }

    // do things as were in componentDidUpdate

    // clean up
    return () => {
        //
    }
},[]) // some value as array who will change and this need to be called 

答案 1 :(得分:0)

Yopu应该将一个空数组作为参数传递

useEffect(() => {
  if(once.current === false){
     // do things as were in componentDidMount    
     once.current = true  
  }
  return () => {
      // this area will fired when component unmounts
  }
}, []) // by providing an empty array this useEffect will act like componentDidMount

如果要在状态更改时重新呈现useEffect,可以将状态添加到空数组中,这样它将监听状态更改并执行

const [someStateValue, setSomeStateValue] = useState('')
useEffect(() => {
  ...
}, [someStateValue]) // will be executed if someStateValue changes

如果您想将componentDidMount和componentDidUpdate结合使用,我脑中有一个可行的解决方案

const [val, setVal] = useState('asd')
const [oldVal, setOldVal] = useState('')

useEffect(() => { // componentDidMount
  if(val !== oldVal){ // componentDidUpdate
     // pass val to old val
     setOldVal(val)
     // set new val to new val
     setVal("theNewestVal") 
  }

  return () => { // componentWillUnmount
     ...
  }

}, [val]) // will be executed if someStateValue changes