【问题标题】:Error Converting a React Class Component to a Function Component将 React 类组件转换为函数组件时出错
【发布时间】:2021-12-10 05:42:57
【问题描述】:

我正在尝试将this demo 转换为函数组件。我正在关注these steps,但我遇到了以下问题:

班级版本:

     this.appointmentForm = connectProps(AppointmentFormContainer, () => {
      const {
        editingFormVisible,
        editingAppointment,
        data,
        addedAppointment,
        isNewAppointment,
        previousAppointment,
      } = this.state;

函数转换尝试:

const [appointmentForm, setappointmentForm] = useState({});


     setappointmentForm(connectProps(AppointmentFormContainer, () => {
      const {
        editingFormVisible,
        editingAppointment,
        data,
        addedAppointment,
        isNewAppointment,
        previousAppointment,
      };

这个版本的错误(尝试了几个)是:“解析错误:'常量声明'需要一个初始化值。”它指的是 setappointmentForm 下的行中的 const 但摆脱它也是不正确的。如果需要整个代码,我会放它,但它很长。有什么想法吗?

【问题讨论】:

    标签: javascript reactjs react-hooks es6-class


    【解决方案1】:

    const 声明没有右手边。这样做是不合法的javascript:

    const foo;
    

    你还需要给它一个值,如

    const foo = "bar";
    

    看起来您正在尝试对状态对象进行解构。在函数组件中,将状态拆分而不是放在单个对象中是很常见的,因此您可能根本不想执行此解构语句,而是执行独立状态。例如:

    const [editingFormVisible, setEditingFormVisible] = useState();
    const [editingAppointment, setEditingAppointment] = useState();
    const [data, setData] = useState();
    // ... etc
    

    如果你不想拆分状态,又想继续做解构赋值,那么把要解构的对象放在右手边。

    const {
      editingFormVisible,
      editingAppointment,
      data,
      addedAppointment,
      isNewAppointment,
      previousAppointment,
    } = someObject; // <------- added
    

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2022-01-17
      • 2020-01-02
      • 2017-09-27
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多