简体   繁体   English

将 React 类组件转换为函数组件时出错

[英]Error Converting a React Class Component to a Function Component

I am trying to convert this demo into a function component.我正在尝试将此演示转换为功能组件。 I am following these steps and I am stuck with the following:我正在遵循这些步骤,但我坚持以下几点:

Class version:课堂版本:

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

Function conversion attempt:函数转换尝试:

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


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

The error with this version (tried several) is : "Parsing error: 'Const declarations' require an initialization value."此版本的错误(尝试了几次)是:“解析错误:'Const 声明'需要一个初始化值。” it refers to the const in the line under the setappointmentForm but getting rid of it is incorrect as well.它指的是 setappointmentForm 下一行中的 const,但摆脱它也是不正确的。 If the whole code is needed I will put it but it is quite long.如果需要整个代码,我会放它,但它很长。 Any ideas?有任何想法吗?

There's no right hand side to your const declaration.你的const声明没有右手边。 It's not legal javascript to do just this:这样做是不合法的javascript:

const foo;

You need to also give it a value, as in你还需要给它一个值,如

const foo = "bar";

It looks like you're trying to do destructuring of a state object.看起来您正在尝试对状态对象进行解构。 In function components, it's common to split up your state instead of having it be in a single object, so you may not want to do this destructuring statement at all, but instead do independent states.在函数组件中,通常将状态拆分而不是将其放在单个对象中,因此您可能根本不想执行此解构语句,而是执行独立的状态。 For example:例如:

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

If you don't want to split up the state and want to keep doing the destructuring assignment, then put the object to destructure on the right hand side.如果您不想拆分状态并希望继续进行解构赋值,则将要解构的对象放在右侧。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM