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

如何将React类组件转换为函数组件?附示例代码

将React类组件转换为函数组件的实现方案

以下是转换后的完整函数组件代码,以及核心转换要点的说明:

import axios from 'axios';
import React, { useState, useEffect } from 'react';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css"

const EditExercise = () => {
  // 用useState替代类组件的state初始化
  const [username, setUsername] = useState('');
  const [description, setDescription] = useState('');
  const [duration, setDuration] = useState(0);
  const [date, setDate] = useState(new Date());

  // 用useEffect替代componentDidMount,空依赖数组确保仅挂载时执行一次
  useEffect(() => {
    const exerciseId = window.location.toString().split('/')[4];
    axios.get(`http://localhost:5000/exercises/${exerciseId}`)
      .then(response => {
        setUsername(response.data.username);
        setDescription(response.data.description);
        setDuration(response.data.duration);
        setDate(new Date(response.data.date));
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  // 事件处理函数:无需绑定this,直接调用状态更新函数
  const onChangeUsername = (event) => {
    setUsername(event.target.value);
  };

  const onChangeDescription = (event) => {
    setDescription(event.target.value);
  };

  const onChangeDuration = (event) => {
    setDuration(event.target.value);
  };

  const onChangeDate = (newDate) => {
    setDate(newDate);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    alert("Exercise Edited!");

    const exercise = {
      username,
      description,
      duration,
      date
    };

    console.log(exercise);
    const exerciseId = window.location.toString().split('/')[4];
    axios.post(`http://localhost:5000/exercises/update/${exerciseId}`, exercise)
      .then(res => console.log(res.data));

    window.location = '/';
  };

  return (
    <div className="EditExercise">
      <h1>Edit Exercise</h1>
      {/* 优化:将表单提交事件绑定到form标签,符合原生HTML行为 */}
      <form onSubmit={onSubmit}>
        <div>
          <label>Username: </label>
          <input
            type="text"
            required
            value={username}
            onChange={onChangeUsername}
          />
        </div>
        <div>
          <label>Description: </label>
          <input
            type="text"
            required
            value={description}
            onChange={onChangeDescription}
          />
        </div>
        <div>
          <label>Duration: </label>
          <input
            type="text"
            required
            value={duration}
            onChange={onChangeDuration}
          />
        </div>
        <div>
          <label>Date: </label>
          <div>
            <DatePicker
              selected={date}
              onChange={onChangeDate}
            />
          </div>
        </div>
        <div>
          <input
            type="submit"
            value="Edit Exercise Log"
          />
        </div>
      </form>
    </div>
  );
};

export default EditExercise;

核心转换要点

1. 状态管理:从this.state到useState Hook

  • 类组件通过this.state集中管理状态,函数组件用useState将每个状态拆分为独立的「状态变量+更新函数」,比如const [username, setUsername] = useState(''),第一个值是当前状态,第二个是更新该状态的专属函数。
  • 无需再写constructor初始化状态,直接在函数内部调用useState即可。

2. 生命周期:从componentDidMount到useEffect Hook

  • 类组件的componentDidMount用于组件挂载后执行一次性逻辑(如请求初始化数据),函数组件中用useEffect实现,第二个参数传空数组[]表示该逻辑仅在组件挂载时执行一次,与componentDidMount执行时机完全一致。

3. 事件处理:移除this绑定

  • 类组件需要在constructor中绑定this才能在事件函数中访问this.state,函数组件中无需绑定,因为事件函数直接定义在组件内部,可以直接访问状态变量和更新函数。

4. 模板渲染:简化状态访问

  • 类组件渲染时用this.state.xxx访问状态,函数组件直接使用对应的状态变量(如username代替this.state.username)。
  • 额外优化:将表单提交事件从按钮的onClick移到<form>标签的onSubmit,更符合HTML原生表单行为。

内容的提问来源于stack exchange,提问作者Frenkie Wang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:07:21