React类组件转函数组件时报Const声明需初始化错误怎么解决
React类组件转函数组件connectProps用法报错解决方案
错误根因
- 直接语法错误:你的解构赋值语句
const { editingFormVisible... }只写了声明部分,缺少右侧的赋值对象,类组件中赋值源是this.state,函数组件中需要对应到你声明的状态变量 - 用法逻辑错误:
connectProps不需要存入useState中,它是基于当前状态生成绑定后组件的工具方法,不需要通过setState触发更新
正确实现步骤
- 首先声明对应类组件state的所有状态变量:
// 字段和原来类组件state中的字段完全对应,可根据实际需求调整初始值 const [editingFormVisible, setEditingFormVisible] = useState(false); const [editingAppointment, setEditingAppointment] = useState(null); const [data, setData] = useState([]); const [addedAppointment, setAddedAppointment] = useState({}); const [isNewAppointment, setIsNewAppointment] = useState(false); const [previousAppointment, setPreviousAppointment] = useState(null);
- 用
useMemo缓存connectProps的返回结果,关联依赖状态:
import { useMemo } from 'react'; // 直接生成绑定属性后的组件,不需要存入state const appointmentForm = useMemo(() => { return connectProps(AppointmentFormContainer, () => { // 直接返回所有需要传递给组件的属性 return { editingFormVisible, editingAppointment, data, addedAppointment, isNewAppointment, previousAppointment, }; }); // 依赖项为所有用到的状态变量,状态变化时自动重新绑定属性 }, [editingFormVisible, editingAppointment, data, addedAppointment, isNewAppointment, previousAppointment]);
额外注意点
- 如果你的状态是存在一个统一的state对象而非单独声明,解构时赋值为对应的state对象即可,比如
const { editingFormVisible } = state - 不要在组件渲染的顶层直接调用
setappointmentForm,会触发无限重渲染
内容的提问来源于stack exchange,提问作者Kahalon
相关产品推荐
相关产品推荐

