【问题标题】:Converting componentWillReceiveProps function to react hooks将 componentWillReceiveProps 函数转换为反应钩子
【发布时间】:2020-08-06 21:32:27
【问题描述】:

大家好,给定一个基本的反应组件,它有componentWillReceiveProps。我想将其转换为使用反应钩子。现在我已经查看了这个问题here,虽然答案很简单,但我觉得我好像错过了一些理解。例如:

export class Example extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillReceiveProps(nextProps) {
    console.log('HELLO WORLD') // Note this isn't called on initial render
    if (nextProps.match.params.id != this.props.match.params.id) {
      console.log('testing....')
    }
  }

  render() {
    return (
      <div>Cool</div>
    );
  }
}

我从上面的例子中知道,除非 nextProps 没有改变,否则我们不会进入 if 语句。现在将上面的转换为函数组件是这样的:

export const Example = ({ ...props }) => {
  useEffect(() => {
    console.log('TESTING')
  }, [props.match.params.id])

  return (
    <div>Cool</div>
  )
}

我还准备了我所见内容的简短记录 gif。 https://recordit.co/hPuwGey6WM

【问题讨论】:

  • 要添加依赖项,您需要使用数组。 useEffect(function(0 {}, [props.match.params.id]); 话虽如此,我认为它总是会在第一次渲染时运行
  • @SerShubham - 抱歉,即使使用数组语法,你也是对的,我看到了同样的事情。你会在录音中看到这一点。
  • useEffect 总是在第一次挂载时运行
  • 对.. 那么我该如何正确模拟:componentWillReceiveProps 的行为。因为这不会在第一次挂载时运行。
  • @Jagrati - 我知道如果你不想在第一次挂载时运行效果,你必须传入一个空数组来使用效果。但这意味着我不会观察任何属性。

标签: reactjs react-hooks


【解决方案1】:

不幸的是,useEffect 被设计为在第一次渲染时运行,并且每次它的依赖关系发生变化。

为避免在第一次渲染时运行,您必须编写自己的小自定义钩子。

const useComponentWillReceiveProps = (callback, dependencies) => {
  const [firstRender, setFirstRender] = useState(true);

  useEffect(() => {
     if(firstRender) {
        setFirstRender(false);
        return;
     }
     callback();
  }, dependencies);
}

或者,您也可以使用 refs 来避免最初的重新渲染,例如:

const useComponentWillReceiveProps = (callback, dependencies) => {
   const firstRender = useRef(true);

  useEffect(() => {
     if(firstRender.current) {
        firstRender.current = false;
        return;
     }
     callback();
  }, dependencies);
}

【讨论】:

    【解决方案2】:

    useEffect 总是在第一次渲染后运行。如果你不想在第一次渲染时运行useEffect,你可以结合useRef使用它

    const Example = ({ ...props }) => {
      const initialRender = useRef(true)
      useEffect(() => {
        if (initialRender.current) {
          initialRender.current = false;
        } else {
          // write code here
          console.log("TESTING");
        }
      }, [props.match.params.id]);
    
      return <div>Cool</div>;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2019-09-01
      • 2022-01-23
      • 1970-01-01
      • 2018-12-16
      相关资源
      最近更新 更多