You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用useEffect重写类组件的componentWillReceiveProps代码?

useEffect 重写实现方案

首先在函数式组件内引入需要的Hooks:

import { useState, useEffect } from 'react';
// react-router v5 引入useHistory
import { useHistory } from 'react-router-dom';
// 如果是react-router v6 替换为引入useNavigate
// import { useNavigate } from 'react-router-dom';

组件核心实现逻辑如下:

const YourComponent = (props) => {
  // 声明errors状态,替代类组件的this.state
  const [errors, setErrors] = useState({});
  // react-router v5 路由跳转实例
  const history = useHistory();
  // react-router v6 路由跳转实例
  // const navigate = useNavigate();

  useEffect(() => {
    // 对应原逻辑的登录状态校验跳转
    if (props.auth?.isAuthenticated) {
      history.push("/dashboard");
      // v6写法替换为
      // navigate("/dashboard");
    }

    // 对应原逻辑的errors状态同步
    if (props.errors) {
      setErrors(props.errors);
    }
  // 依赖数组监听对应props变化,和原componentWillReceiveProps触发逻辑一致
  }, [props.auth, props.errors, history])

  // 其余组件业务逻辑...
}

关键说明

  • componentWillReceiveProps的核心是监听指定props变化后执行副作用操作,对应useEffect的实现就是把需要监听的变量放到依赖数组中,依赖项更新时就会触发回调执行,和原生命周期效果完全一致
  • 代码中加入了可选链?.处理auth为undefined的边界情况,你可以根据实际业务场景调整
  • 无旧版本兼容需求的前提下,优先使用react-router v6的useNavigate写法即可

内容的提问来源于stack exchange,提问作者David Momoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:39:01